使可观察的呼叫在角度9中同步

时间:2020-08-09 16:43:40

标签: angular rxjs observable angular8 angular9

我正在使用可观察的HTTP请求,因为它是rxjs的新手,所以我希望将其作为同步调用。下面的代码习惯于执行多个调用,因此在完成所有调用之后,我只需要调用drive方法。我提到了很多链接,但我不明白请帮忙。

ServicecallApi:

public createHttpRequests(
    method: string,
    url: string,
    payload?: any,
    params?: any,
 
  ): Observable<any> {
    switch ((method).toLowerCase()) {
      case 'get': return this.createHttpGet(url, params);
      case 'post': return this.createHttpPost(url, payload);
      default: return this.http.get('');
    }
  }

我的服务电话如下:

  public ngOnInit(): void {


this.serviceCall.createHttpRequests('get', this.someService.getUserList, {}, {}).pipe(
  map((result: Iuserlist) => {
    if (result.body.statusCode ===  200) {
    
    } else {
   
    }
  }),
).subscribe();
this.serviceCall.createHttpRequests('get', this.someService.getsomeData, {}, {}).pipe(
  map((result: Isomedatas) => {
    if (result.body.statusCode ===  200) {
    
    } else {
   
    }
  }),
).subscribe();

//This method should call after the above api completion 
this.getDriverDetails();
 }

2 个答案:

答案 0 :(得分:1)

为此,您可以使用combineLatest中的rxjs函数。

使用以下代码。

public createHttpRequests(
  method: string,
  url: string,
  payload? : any,
  params? : any,

): Observable<any> {
  switch ((method).toLowerCase()) {
    case 'get':
      return this.createHttpGet(url, params);
    case 'post':
      return this.createHttpPost(url, payload);
    default:
      return this.http.get('');
  }
}
// And my service call is below:
public ngOnInit(): void {
  const userList$ = this.serviceCall.createHttpRequests('get', this.someService.getUserList, {}, {}).pipe(
    map((result: Iuserlist) => {
      if (result.body.statusCode === 200) {

      } else {

      }
    }),
  );

  const someData$ = this.serviceCall.createHttpRequests('get', this.someService.getsomeData, {}, {}).pipe(
    map((result: Isomedatas) => {
      if (result.body.statusCode === 200) {

      } else {

      }
    }),
  );

  combineLatest([userList$, someData$]).subscribe(([userList, someData]) => {
    console.log(userList);
    console.log(userList);

    this.getDriverDetails();
  });
}

答案 1 :(得分:0)

使用async/await可以实现可观察的同步,但是我认为这是一个坏主意,一种更好的方法是使用forkJoin,因为一旦要执行2个可观察的操作,您就要执行代码完成。

forkJoin({
  firstService: this.firstService$,
  secondService: this.secondService$});
.subscribe({
 next: value => {
  //this  will run once both observables are completed. 
  console.log(value); 
  // Logs:
  // { firstService: response, secondService: response, } 
  //call your function here 
  this.getDriverDetails();
  }
});
 
相关问题