【问题标题】:Using HttpClient to make get requests使用 HttpClient 发出 get 请求
【发布时间】:2021-12-09 16:00:45
【问题描述】:

我已经编写了以下代码来获取虚拟数据here

export class AppComponent {
    
  jsonPosts: any = [];

  constructor(private httpClient: HttpClient) { }

  OnInit() {
    this.getJsonPosts();
  }

  getJsonPosts(): any {
    return this.httpClient.get("https://jsonplaceholder.typicode.com/posts")
      .subscribe(response => {
        console.log(response);
        this.jsonPosts = response;
      });
  }

我还编写了以下代码以在我的 HTML 模板中显示它们:

  <ul *ngFor="let i of jsonPosts">
    <li>{{i.userId}}</li>
    <li>{{i.id}}</li>
    <li>{{i.title}}</li>
    <li>{{i.body}}</li>
  </ul>

但是,根本没有网络活动,因此没有任何显示...

我在这里做错了什么?

【问题讨论】:

标签: html json angular typescript http


【解决方案1】:

你没有调用OnInit 方法。如果你想让 Angular 生命周期调用你的方法,你的组件必须实现 OnInit 接口和 ngOnInit 方法。

更多here.

所以你的组件代码应该是这样的:

export class AppComponent implements OnInit {
    
  jsonPosts: any = [];

  constructor(private httpClient: HttpClient) { }

  ngOnInit(): void {
    this.getJsonPosts();
  }

  getJsonPosts(): any {
    return this.httpClient.get("https://jsonplaceholder.typicode.com/posts")
      .subscribe(response => {
        console.log(response);
        this.jsonPosts = response;
      });
  }

【讨论】:

    猜你喜欢
    • 2019-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多