Angular7 在运行下一个函数之前接收 API 数据 [英] Angular7 Receive API data before running next function

查看:24
本文介绍了Angular7 在运行下一个函数之前接收 API 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to receive data from API before running next function in angular7

'data.service.ts

'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

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: 真

Actual print out: ZoneAwarePromise {__zone_symbol__state: null, __zone_symbol__value: Array(0)} __zone_symbol__state: true

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

Expected print out: the json object received

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

I would like to run some function to deal with the data before displaying them in html, so I need to have the data loaded inside the class.

除了将 next_function 放在 getDATA() 中,还有其他方法吗?

Would there be other method except putting the next_function inside the getDATA()?

推荐答案

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

What you can do here is return the Observable from the http call and subscribe to that.

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

这篇关于Angular7 在运行下一个函数之前接收 API 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆