angular - 调用已订阅的方法如何等待订阅返回类型?
问题描述
所以我的问题希望相对容易解决。所以(Angular 8 btw)我调用了一个方法,并在该方法内部订阅了一个 api 调用。一切正常,除了返回总是在方法之后一两秒后被调用,并且返回类型永远不会正确返回。我尝试了 MAP,但它不能正常工作。让我编写一个简单的示例:
return this.callApi( apiObject ); // I want to wait for subscribe and return data here
callApi( apiObject ) {
this.myApiService.someRandomPostApiCall( apiObject ).subscribe(res => {
console.log(res);
res.valid ? { return true } : { return false };
});
}
解决方案
如果您想在发出项目时做出反应(基本上等到检索数据),最好的办法是在您需要它的组件中订阅,而不是在函数本身中订阅。
return this.callApi( apiObject ).subscribe(//do stuff here);
callApi( apiObject ) {
return this.myApiService.someRandomPostApiCall( apiObject )
}
这是我的一个应用程序的示例:
在服务中
getProducts(): Observable<IProduct[]> {
return this.http.get<IProduct[]>(this.productUrl)
.pipe(
tap(data => console.log('All: ' + JSON.stringify(data))),
catchError(this.handleError)
);
}
在一个组件中
ngOnInit(): void {
this.productService.getProducts().subscribe({
next: products => this.products = products,
error: err => this.errorMessage = err
});
}
您可以在此处查看整个源代码:
https://stackblitz.com/edit/github-angular-getting-started-final
推荐阅读
- javascript - 从 2 个点和半径计算圆弧的中点
- python - PyQt5 - QTableView + QAbstractTableModel - html 格式单元格/列文本
- r - 在 R 中使用 ggplots 制作趋势变化图
- linux - 如何只允许来自某个 USB 端口的某些键命令
- css - Css - menu-wrapper 的显示定位问题
- powershell - 设置 PowerShell Azure SQL 连接字符串参数
- android - Android Studio - 检测到 Vanguard(检测到不兼容的软件),而它甚至没有作为进程安装或打开
- c++ - 在联合崩溃程序中分配 std::function
- python - 如何通过检查值将键添加到字典
- angular - 离子电容器本地通知