angular - 当订阅方法成功完成时,如何初始化响应的某些属性 - 在完整方法中?
问题描述
有一个 api post 方法有时会失败。如果失败,我会在页面上显示错误消息。但有时当 api 出现错误时,它仍然进入下一个方法,然后我有错误。我想确定什么时候没有错误,所以在即将到来的响应中初始化我的属性的完整方法。我的代码看起来像这样。
this.attService.postUser(user).subscribe((response: any) => {
this.postRequestResponse = response;
this.selectedServiceSpeedsArr.push(this.selectedServiceSpeed);
let index = this.selectedAttService[0].serviceSpeeds.findIndex(item => item.id == event.id);
}, (err) => {
this.makeQuoteErrorMessage = 'Something went wrong.Please try again';
}, () => {
console.log("success");
//can i done something like this ?
myProperty = response;
})
}
解决方案
是的,你可以,正如你在这里看到的:
export class MyComponent implements OnInit {
constructor(private http: HttpClient) {}
ngOnInit() {
let result = this.http.get(<YOUR_URL>);
result.subscribe(
res => {
// this is your response with no errors
},
err => {
// here you handle your errors
},
() => {
// here is the finally block where you can do things either you got errors or not
}
);
}
}
你可能想试试这个,祝你好运!
推荐阅读
- asynchronous - Julia @distributed:后续代码在所有工作人员完成之前运行
- docker - docker容器中的高效svn结帐
- dbus - gdbus introspect 与 --recurse 和 --xml 选项一起不递归
- grep - grep - 从字符串中获取单词
- javascript - Mongoose 5.3,this.getUpdate 不是函数
- html - CSS 定位无序列表中的顶级 p 标签
- typescript - 基于 Koa 使用默认和命名导出创建可扩展的打字稿包
- c - 如何从 C 中的链表构建霍夫曼树?
- c# - LINQ To Entities - M 到 M 选择返回比需要更多的列
- javascript - 在 PHP Laravel 中将变量从 foreach 循环传递到我的控制器