如何解决如何从其他页面中的方法获取结果 - Angular
我有一个 service.ts 文件,其中有一个更新标志的函数:
service.ts
setReconciliationFlag(id: string,subPostingId: string,isReconciled: string) {
const requests = this.bmlService.get(BmlRequest.SetReconciled,{
bwtxnid: id,bwpostingid: subPostingId,isreconciled: isReconciled,});
requests.pipe(take(1)).subscribe(
(response) => {
if (response && response.success) {
return response;
} else {
return throwError({ message: response.error });
}
},(error) => {
return throwError({ message: error });
}
);
}
然后在 component.ts 我调用这个方法:
setReconciliationFlag(id: string,isReconciled: string) {
this.transactionHistoryStatementService.setReconciliationFlag(
id,subPostingId,isReconciled
);
}
哪个有效,方法得到调用,标志得到更新,但你如何将响应返回给组件?如果我使用 then
或 subscribe
或 pipe
,我会收到错误 Property 'then' does not exist on type 'void'
解决方法
您必须在服务中使用 Subject 来发出新值,并将其作为 Observable 从组件中订阅以接收更改。
在这篇文章中有一个简单的例子(第 3 点):https://www.digitalocean.com/community/tutorials/angular-component-communication
附言记得在组件 ngOnDestroy 中取消订阅。
,您不应该订阅服务,您的服务功能也不会返回任何响应。根据您的用例,您可以返回 Promise 或 Observable。
setReconciliationFlag(id: string,subPostingId: string,isReconciled: string): Promise<any> {
return this.bmlService.get(BmlRequest.SetReconciled,{
bwtxnid: id,bwpostingid: subPostingId,isreconciled: isReconciled,}).pipe(take(1)).toPromise().then(response => {
if (response && response.success) return response;
else throw new Error({ message: response.error });
}).catch(error => {
throw new Error({ message: error });
});
}
在组件中,
setReconciliationFlag(id: string,isReconciled: string) {
this.transactionHistoryStatementService.setReconciliationFlag(id,subPostingId,isReconciled).then(response => {
console.log(response)
});
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。