无法获取 api 的数据

Unable fetch the api's data

我有一个名为 customer 的组件,它用于使用 api.

显示一些数据

For calling the api i have created a file called services.ts and it's CODE looks like this:

services.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { IPosts } from './models';

@Injectable()
  export class Service {
      constructor(private http: HttpClient) {}

   public getContactList(): Promise<IPosts> {
    const apiUrl: string = 'https://jsonplaceholder.typicode.com/posts'; // dummy API

    return this.http.get<IPosts>(apiUrl).toPromise();
   }
 }

As shown in the code an interface (IPosts),I have declared this interface(i,e IPosts) inside an file called models.ts. The CODE looks like this:

   export interface IPosts {
    userId: number;
    id:     number;
    title:  string;
    body:   string;
    }

Now i am displaying this api's data incustomer component is like this:

customer.html

   <div class="container">
        <h3>Blog Posts:</h3>
      <div class="blogPost " *ngFor = "let post of posts">
           <p>{{post.title}}</p>
           <p>{{post.body}}</p>
           <hr>
      </div>
  </div>

customer.ts

  import { Component, OnInit } from '@angular/core';
  import { Service } from '../service';
  import { map } from 'rxjs/operators';
  import { IPosts } from '../models';

  @Component({
   selector: 'app-customer',
   templateUrl: './customer.component.html',
   styleUrls: ['./customer.component.css']
  })

  export class CustomerComponent implements OnInit {
          constructor(public customersServiceList: Service) {}

  public async ngOnInit(): Promise<void> {
    const posts : IPosts = await this.customersServiceList.getContactList();
    console.log(posts);
    }

  }

我可以在控制台中看到 api 的数据:

但无法在 .html 文件中显示。调用 api 有什么问题。
这是 stckblitz DEMO

像这样更改 CustomerComponent

export class CustomerComponent implements OnInit {

  constructor(public customersServiceList: Service) {}
  posts : IPosts[];
  public async ngOnInit(): Promise<void> {
      this.posts  = await this.customersServiceList.getContactList();
      console.log(this.posts);
   }
 }

服务

 public getContactList(): Promise<IPosts[]> {

    const apiUrl: string = 'https://jsonplaceholder.typicode.com/posts';
    return this.http.get<IPosts[]>(apiUrl).toPromise();
  }

正在检查这里StackBlitz

如果没有 async 调用,您可以使用 .then 从 API 服务获取响应:

在HTML中:

<div class="container">
  <h3>Blog Posts:</h3>
  <br>
  <div class="blogPost " *ngFor="let post of posts">
    <p>{{post.title}}</p>
    <p>{{post.body}}</p>
    <hr>
  </div>
</div>

在 TS 文件中:

posts: any;
constructor(public customersServiceList: Service) { }

ngOnInit() {
  this.customersServiceList.getContactList().then(response => {
    if (response) {
      this.posts = response;
    }
 });

}

StackBlitz Example

You can often use observables instead of promises to deliver values asynchronously. Similarly, observables can take the place of event handlers. Finally, because observables deliver multiple values, you can use them where you might otherwise build and operate on arrays.(from Angular.io)

检查这个 link

可以这样改—— 客户组件

export class CustomerComponent implements OnInit {
 constructor(private customersServiceList: Service) {}

  public ngOnInit() {
    this.getPosts();
  }

  public getPosts(){
    this.customersServiceList.getContactList().subscribe(res => {
    console.log(res[0].title);
  },
  (error) => {
    console.log(error.error);
  });
  }

}

服务

export class Service {

 constructor(private http: HttpClient) {
  }


  public  getContactList(): Observable<IPosts[]> {
    const apiUrl: string = 'https://jsonplaceholder.typicode.com/posts';

    return this.http.get<IPosts[]>(apiUrl);
  }
}