首页 > 解决方案 > 当订阅方法成功完成时,如何初始化响应的某些属性 - 在完整方法中?

问题描述

有一个 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;
    })
  }

标签: angularrxjs

解决方案


是的,你可以,正如你在这里看到的:

 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
     }
  );
 }
}

你可能想试试这个,祝你好运!


推荐阅读