首页 > 解决方案 > Angular7在运行下一个函数之前接收API数据

问题描述

我想在 angular7 中运行下一个函数之前从 API 接收数据

'数据.service.ts

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

@Injectable({
  providedIn: 'root'
})
export class DataService {

  constructor(private http: HttpClient) { }

  public url = 'https://reqres.in/api/users'
  async getData() {
    await this.http.get(this.url)
    .toPromise()
    .then(
      res => {return res}
    )
  }
}

app.component.ts

  public users
  constructor(private dataservice: DataService) {}

  ngOnInit() {
    this.users = this.dataservice.getData()
    console.log(this.users)
    next_function()
    ....

实际打印输出:ZoneAwarePromise {__zone_symbol__state: null, __zone_symbol__value: Array(0)} __zone_symbol__state: true

预期打印输出:收到的 json 对象

我想在将数据显示为 html 之前运行一些函数来处理数据,所以我需要在类中加载数据。

编辑:除了将 next_function 放入 getDATA() 之外,还有其他方法吗?

标签: angularasynchronoushttpclientangular-promise

解决方案


你可以在这里做的是从 http 调用中返回 Observable 并订阅它。

数据服务.ts

    getData() {
     return this.http.get(this.url);
    }

app.component.ts

this.dataservice.getData().subscribe(resp => {
   this.users = resp; // here you set the users
   next_function(); // this function will be called after getting data from the service
});

推荐阅读