Home > Mobile >  How to conditionally use return inside an observable in angular
How to conditionally use return inside an observable in angular

Time:08-05

I have an angular 13 HTTP call and am subscribing to an observable. How can I conditionally call a return statement based on the length of the object passed as a payload to the HTTP call.

Sample code of what I want to achieve:

public myApiCall(userId: string,customId: string, payload: {}): Observable<any> {
  if(payload.length > 0 ){
    return this.httpClient.post<any>(environment.apiUrlBasePath   environment.USER_DETAILS, payload);
 } else {
   return this.httpClient.post<any>(environment.apiUrlBasePath   environment.NO_USER_DETAILS,payload); 
 }          
}

How can I use a conditional statement inside an angular http call.

CodePudding user response:

payload is defined as an object {} instead of an array. length is not a property of a object.

You can check if the object is undefined, you can also test if the object is empty by getting it properties as an array like this: Object.keys(payload).length === 0

CodePudding user response:

For a more Reactive Approach You can use the RxJs Conditional Operator iff to achieve that.

The iff operator takes 3 arguments, first when being your condition, 2nd and 3rd being your different services that return an Observable.

If the condition is true subscribe to the first observable (HTTP call), if it is false subscribe to the second observable

 iif(
      () => {
           //Add your condition here
           return payload.length > 0;
         },
       this.httpClient.post<any>(environment.apiUrlBasePath   environment.USER_DETAILS, payload),
       this.httpClient.post<any>(environment.apiUrlBasePath   environment.NO_USER_DETAILS,payload)
     )
     .pipe(takeUntil(this.unsubscribe$))
     .subscribe((items)=> {
         this.someData = items;
     });
  • Related