angular - 服务方法不返回承诺
问题描述
目前在我的 Angular 8 应用程序中,当发生异常时,promise call 不会返回异常。有人可以告诉我如何让 getRepApprovedName 返回一个承诺。如果我使用 return http.get,我会收到一个语法错误,提示需要大括号。
零件
private getRepCode = (repCode: string) => {
this.loading = true;
const repToSend = fromGenistarCode(repCode);
if (repToSend === 0) {
this.splitSaleDetails.repName = '';
return;
}
this.inviteService.getRepApprovedName(repToSend, this.currentUserId).then(rep => {
if (rep) {
this.splitSaleDetails.repName = rep.name;
} else {
this.splitSaleDetails.repName = '';
}
this.fieldDataChanged(new SetSplitSaleDetails(this.splitSaleDetails));
this.loading = false;
}).catch((err) => {
console.log(err.message);
return this.messageService.add(err.message, 'warning', true);
});
服务
public getRepApprovedName = (repId: number, loggedInUserId: number): Promise<any> =>
this.http.get(`${this.baseUrl}representative-name/${repId}/${loggedInUserId}`).toPromise()
建议的解决方案
this.inviteService.getRepApprovedName(repToSend, this.currentUserId).subscribe(rep => {
if (rep) {
this.splitSaleDetails.repName = rep.name;
} else {
this.splitSaleDetails.repName = '';
}
this.fieldDataChanged(new SetSplitSaleDetails(this.splitSaleDetails));
this.loading = false;
},
error => {
this.messageService.add(error.message, 'warning', true);
});
public getRepApprovedName = (repId: number, loggedInUserId: number): Observable<any> =>
this.http.get(`${this.baseUrl}representative-name/${repId}/${loggedInUserId}`)
解决方案
您应该使用Observable
withHttpClient
和subscribe
方法。
this.inviteService.getRepApprovedName(...).subscribe(
result => {
// ok
},
error => {
// catch error
}
);
你的get
方法:
getRepApprovedName(...): Observable<YourResultType> {
return this.http.get<YourResultType>(...your url...);
}
HttpClient
get 方法返回一个Observable
并且会在出现任何问题时自动捕获错误。
推荐阅读
- python - 将y轴自动缩放到pyqtgraph中的可见数据
- node.js - 从一个目录中的所有 ts 文件中收集导出
- javascript - 使用单个 JSON Web 令牌在 MongoDB 中创建多个文档
- ios - 在 Xamarin Forms 应用中使用 iOS 特定元素
- node.js - Heroku 上的 MERN 不能跨浏览器工作
- android - RecyclerView GridLayoutManager - 交替 3 和 2 列行
- php - 如何使用 PHP 预览图像
- iis - 尝试其他建议的解决方案后无法启动 Windows Process Activation Service
- webpack - Webpack 配置扩展
- php - Laravel 5.6 - 尝试检索图像时权限被拒绝