Angular http get 什么都不做

Angular http get does nothing

我正在学习 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 上的站点与我添加 "posts" 之前的站点相同。在我编译时或在 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

不要将旧模块用于 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;
          })
      );
  }