无法获取API的数据

时间:2018-12-05 05:49:31

标签: angular api model angular-services

我有一个名为customer的组件,用于使用 api 显示一些数据。

  

为调用api,我创建了一个名为services.ts的文件,它的CODE看起来像这样:

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();
   }
 }
  

如代码interface(IPosts)所示,我已在名为models.ts的文件中声明了此接口(即IPosts)。该代码如下所示:

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

现在我正在api's组件中显示此customer数据,就像这样:

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的数据:

enter image description here

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

3 个答案:

答案 0 :(得分:2)

没有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

答案 1 :(得分:1)

像这样更改 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();
  }

在这里{@ 3}}

答案 2 :(得分:1)

  

您通常可以使用可观察变量代替承诺来传递价值   异步地。同样,可观察对象可以代替事件   处理程序。最后,由于可观测值传递多个值,因此您   可以在您可能会在上面构建和运行的地方使用它们   数组。(来自Angular.io)

选中此link

可以这样更改- CustomerComponent

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);
  }
}