Home > database >  Returning a Property from Observable as Observable in Rxjs Angular
Returning a Property from Observable as Observable in Rxjs Angular

Time:11-07

Iam new to angular and Observables .My Rest API always return a custom response type

 export class CustomApiResponse {
      isSucess: boolean | undefined; //  denotes whether request was sucess
      statusCode: number | undefined; //  custom status codes from webapi 
      error: string | undefined;      // error message in case of error
      value: any;                 //data which may be array of object or single object
    }

I am having a generic service for all httprequest

export class HttpHelperService {
  BaseUrl:String="mydominurl/api";
  constructor( private httpclient :HttpClient) { }

   GetData(url:string) : Observable<CustomApiResponse>{
    return  this.httpclient.get<CustomApiResponse>(this.BaseUrl url);
   }
  }

Now I need to call this httphelper and extract the data from the response as observable using my services like below (Which Iam not able to figure out)

export class CategoryService {
  url:String="/api_category";
  constructor( private httphelper :HttpHelperService) {  }

   getCategories(url:string) : Observable<Category[]>{   

     this.httphelper.GetData(url).subscribe(val=>{
      if(val.isSucess){ 
     return val.value; //How to do this
     }} );  }

}

Please advice me how to rewrite above method so that I can call the above services from my components like below

export class CategoryListComponent implements OnInit {

  Items: Observable< Category[]> | undefined;
  url:string="/Api_category";
  constructor( private catservice :CategoryService) {
  }

  ngOnInit(): void {
    this.catservice.getCategories(this.url).subscribe(val=> this.Items=val);
  }
}

CodePudding user response:

I think what you are trying to do is modify the value that is provided to the CategoryListComponent, after getting a reply from the HttpHelper.

This can be done using the map operator, like this:

export class CategoryService {
  url:String="/api_category";
  constructor( private httphelper :HttpHelperService) {  }

   getCategories(url:string) : Observable<Category[]>{   
     return this.httphelper.GetData(url).pipe(map((val) => val.isSuccess ? val.value : []));
   }

}

This will return a new observable that will change the value of the response from GetData to something else (in this case, val.value if the val.isSuccess was true, and otherwises an empty list).

Then your component is going to subscribe and it will work fine.

Always try to subscribe to observables as the very last step of a long chain of observables. It is going to require a lot of learning of RxJS but it is the proper way to do it, ideally you will have your component subscribe to the observable and the rest of intermediate services will be mapping, filtering, transforming or combining the information.

  • Related