【发布时间】:2021-09-25 21:36:00
【问题描述】:
我有一个函数 getData(),它调用 API、处理数据、转换并将其保存到 BehaviorSubject。然后使用 of() 将处理后的数据作为 observable 返回。
getData()
getData(fId: string | null = null) {
// get the data to tempItems with an API Call
this.getDataFromAPI().subscribe(data => {
this.tempItems = [data]
})
let items = cloneDeep(this.tempItems);
// Separate the items by folders and files
const a: Item[] = items.filter(item => item.type === 'a');
const b: Item[] = items.filter(item => item.type !== 'b');
const path: Item[] = [];
//do some work
// Create data
let data = {
folders: a,
files: b,
path
}
// Add this data to the BehaviorSubject
this._items.next(data);
return of(data);
}
getDataFromAPI()
getDataFromAPI() {
return this._httpClient.get(URL);
}
在getData() 函数中,变量this.tempItems 在运行时未定义。由于 HTTP 调用,脚本的其余部分不会等待 HTTP 请求完成。
如何在此处正确使用 Async Await?仍然,设法返回of(data)
调用 getData() 函数的函数期望返回一个 observable
【问题讨论】:
-
调用
getData()函数的函数需要一个可观察的返回 -
并非如此。我正在将此服务与解析器一起使用。并从
ngOnInit中的 BehaviourSubject 访问数据
标签: angular typescript async-await observable