Angular7 在运行下一个函数之前接收 API 数据



我想在 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:真

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

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

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

在这里你可以做的是从 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
});

如果你想坚持承诺/异步/等待配方,那么你可以这样做:

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

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

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 错误。您可能还想查看可观察量。

最新更新