Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make observable call synchronous in angular 9

I am using observable for HTTP request I want to make it as a synchronous call since am new to rxjs. And below code am using to doing the multiple calls, so after the completion of all the calls only I have to call the drive method. I referred a lot of links but I could not understand pls help me.

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

And my service call is below:

  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();
 }
like image 474
Sathish Avatar asked Nov 22 '25 10:11

Sathish


1 Answers

For this purpose you can use combineLatest function from rxjs.

Use below code.

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();
  });
}
like image 183
Vivek Jain Avatar answered Nov 25 '25 02:11

Vivek Jain