angular - 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() 之外,还有其他方法吗?
解决方案
你可以在这里做的是从 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
});
推荐阅读
- python - 解析 urllib 请求
- typescript - 函数中的打字稿泛型类型错误
- python-3.x - Python - 具有浅引用的列表连接?
- flutter - 如何使用流实现延迟加载?
- python - 内部服务器错误:/admin/login/DoesNotExist at /admin/login 站点匹配查询不存在`
- arrays - 如何排序以及在 2 列上对 2D 数组进行排序的时间复杂度是多少?
- javascript - 浏览器阻止视频时如何管理视频的自动播放:备份脚本?
- yaml - 无法从 yaml 生成示例 json 值
- java - 在对其键和值进行排序后,将 java 对象打印为 JSON 字符串
- python - 替换长文档中的一组单词