Home > Net >  How to make liner service calls in rxjs or in angular
How to make liner service calls in rxjs or in angular

Time:06-07

I want to achieve scenario like below If 1st service has any values then it should return it If 1st service is not having any response then it second service should be called.

How to achieve this in angular.. or is it possible to achieve it using RXjs operators

CodePudding user response:

You can do something as simple as:

firstService.getValues().subscribe(received => {
    if(received != undefined){
        //do something
    }else{
        secondService.getValues().subscribe(received => {
            //do something else
        }
    }
})

CodePudding user response:

I understand that if the first service is not available, request the second service for information and this can be done as follows

service.ts:

constractor(private http:HttpClient){}

getUser():Observable<any>{
  this.http.get('url_api_one').pipe(
   map((data:any)=>{
    if(data!=undefined)
      return data;
    return this.http.get('url_api_two');
   })
  )
}

CodePudding user response:

With RxJS you can achieve this by combining catchErorr() and switchMap(), assuming that you get a 404 status.

searchItem(firstNumber: number, secondNumber: number): Observable<any> {
  return this.http
    .get('https://jsonplaceholder.typicode.com/posts/'   firstNumber)
    .pipe(
      tap((res) => console.log('Succesfull 1st service result', res)),
      catchError((error) => {
        if (error.status === 404) {
          return of(undefined);
        } else {
          throw error;
        }
      }),
      tap((res) => console.log('After catcherror', res)),
      switchMap((res) =>
        iif(
          () => res === undefined,
          this.http
            .get('https://jsonplaceholder.typicode.com/posts/'   secondNumber)
            .pipe(
              tap((res) => console.log('Succesfull 2nd service result', res))
            ),
          of(res)
        )
      )
    );
}

When you search for something that is not found, catchError will check the status for 404 and then give an observable of undefined, that will be used in the iif in switchMap.

Calling it with a first value that doesn't exist will trigger calling the second service.

ngOnInit() {
    this.searchItem(101, 5).subscribe((res: any) => {
      this.firstSearch = res;
      console.log('SUB', res);
    });

    this.searchItem(1, 5).subscribe((res: any) => {
      this.secondSearch = res;
      console.log('SUB', res);
    });
  }

first call will trigger a 404 and thus will call the 2nd service, the second call will just use the 1st service.

I've used JSONPlaceholder for this, where any id > 100 will trigger a 404 status.

See stackblitz for the working example: https://stackblitz.com/edit/angular-ivy-zffnsh?file=src/app/app.component.ts

  • Related