【问题标题】:Angular7 Receive API data before running next functionAngular7在运行下一个函数之前接收API数据
【发布时间】:2019-10-09 08:57:04
【问题描述】:

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

'data.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() 里面还有其他方法吗?

【问题讨论】:

  • 使函数异步只是意味着它总是返回一个promise,你可以在其中使用await。它不会神奇地让它的调用者同步接收值,他们仍然必须解决承诺。

标签: angular asynchronous httpclient angular-promise


【解决方案1】:

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

data.service.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
});

【讨论】:

    【解决方案2】:

    如果你想坚持 promise/async/await 配方,那么你可以这样做:

    // service
    getData() {
        return this.http.get(this.url).toPromise();
    }
    
    // component
    async ngOnInit() {
        this.users = await this.dataservice.getData();
        console.log(this.users);
        next_function();
    

    【讨论】:

      【解决方案3】:

      您根本不需要在这里使用async/await。您已经在 getData 中使用 toPromise 将 observable 转换为 Promise。您可以简单地返回此承诺并处理组件中的其余部分。

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

      现在在ngOnInit 中使用then 来获取已解决/拒绝的数据。

      ngOnInit() {
          this.dataservice.getData().then(users => {
              console.log(users);
              next_function();
          }, err => {
              console.log(err);
          });
      }
      

      这样,如果您从不同的组件调用getData,您可以处理该组件中的任何 API 错误。您可能还想查看observables

      【讨论】:

        猜你喜欢
        • 2018-05-04
        • 2021-01-26
        • 1970-01-01
        • 1970-01-01
        • 2021-10-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-23
        相关资源
        最近更新 更多