【问题标题】:Angular http get does nothingAngular http get什么都不做
【发布时间】:2020-08-18 03:10:05
【问题描述】:

我正在关注 Udemy 上的教程,但我无法练习如何在 Angular 中使用 HTTP GET。我已经创建了名为 posts 的组件,这里是 posts.component.ts 的代码:

import { Http } from '@angular/http';
import { Component, OnInit } from '@angular/core';


@Component({
  selector: 'app-posts',
  templateUrl: './posts.component.html',
  styleUrls: ['./posts.component.css']
})
export class PostsComponent implements OnInit {
  posts: any[];

  constructor(http: Http) {
    http.get('http://jsonplaceholder.typicode.com/posts')
    .subscribe( response => {
      this.posts = response.json();
    });
   }

  ngOnInit() {
  }
}

还有posts.component.html

<ul class="list-group">
  <li
  *ngFor="let post of posts"
  class="list-group-item">
  {{post.title}}
</li>
</ul>

我还在 app.module.ts 中导入了 HttpModule,但我无法看到任何结果,我在 localhost:4200 上的站点与添加“帖子”之前的站点相同。在我编译或在 Web 浏览器控制台中也没有任何错误。这是我的网络浏览器控制台中的内容:

DevTools failed to load SourceMap: Could not load content for chrome-extension://gighmmpiobklfepjocnamgkkbiglidom/include.preload.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME

Angular is running in the development mode. Call enableProdMode() to enable the production mode.

DevTools failed to load SourceMap: Could not load content for chrome-extension://gighmmpiobklfepjocnamgkkbiglidom/include.postload.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME

【问题讨论】:

  • 这是一个非常古老的 Angular 版本。您最好花时间阅读 angular.io 上的官方文档和指南。您的代码也没有什么特别的问题。它应该像你展示的那样工作,所以你的结果有一些缺失的信息。您应该确定请求是否真的发出,如果是,response.json() 是否返回您期望的结果。

标签: angular http get angular-httpclient


【解决方案1】:

不要将旧模块用于 http 请求:

import { Http } from '@angular/http';

改用新模块:

import { HttpClient } from '@angular/common/http';

这里是一个例子:https://stackblitz.com/edit/angular-http-client-first-example?file=src/app/app.component.ts

编辑: 使用这个版本:

  constructor(
      private readonly _http: HttpClient) {
    this.getPosts().subscribe(res => {
      this.posts = res;
    });
  }

  getPosts(): Observable<any[]> {
    console.log('getPosts');
    return this._http.get('https://jsonplaceholder.typicode.com/todos').pipe(
        map<any, any[]>(response => {
            console.log(response);
            return response;
          })
      );
  }

【讨论】:

  • 谢谢,但我已将代码从示例复制到我的项目中,但我仍然无法在网站上看到任何内容,也无法在 Web 浏览器的控制台中看到任何内容。
  • 你是在说我的例子吗?你有控制台错误吗?您确定已将新模块导入 app.module.ts 吗?导入:[HttpClientModule],
  • 我的错,我很困惑。你能解释一下为什么 hello.component 和 app.component 中都有 http.get 吗?我不明白 app.component 中的 http.get 在做什么。
  • 不要考虑“hello.component”。这是我的第一次尝试。我从示例中删除它。我还通过插入要考虑的代码来修改答案。
猜你喜欢
  • 2016-10-10
  • 1970-01-01
  • 2021-01-17
  • 2016-04-09
  • 1970-01-01
  • 1970-01-01
  • 2011-07-28
  • 2019-03-08
  • 2016-12-24
相关资源
最近更新 更多