Search code examples
angulartypescriptrxjsobservablengrx

How to use the result of an inner observable while using ngrx selector?


In My app, at some point I have the following code :

  this.missionHelperService.checkMissionPoint(position).subscribe(result => {

  });

Now, checkMissionPoint is supposed to do the following =>

  1. -Get a value from a store
  2. -Execute an API call
  3. -Return the API result

I am trying to make it return the result of the observable, but I can't manage to find the correct syntax

  checkMissionPoint(position: Cartographic): Observable<CheckMissionResponse> {
    const params = {
      latitude: CesiumMath.rad2Deg(position.latitude),
      longitude: CesiumMath.rad2Deg(position.longitude),
      altitude: position.height,
    };

    return this.store$.pipe(select(TransactionsStoreSelectors.selectedTransactionId), take(1)).pipe(
      map((tId) => {
        return this.httpClient.post<any>(`${environment.API_URL}/trajectories/${tId}/checkpoints`, params);
      })
    )
  }

How can I do this ?


Solution

  • You can try switchMap, since you are returning a new observable:

    checkMissionPoint(position: Cartographic): Observable<CheckMissionResponse> {
      const params = {
        latitude: CesiumMath.rad2Deg(position.latitude),
        longitude: CesiumMath.rad2Deg(position.longitude),
        altitude: position.height,
      };
    
      return this.store$.pipe(
        select(TransactionsStoreSelectors.selectedTransactionId), 
        take(1),
        switchMap((tId) => {
          return this.httpClient.post<any>(`${environment.API_URL}/trajectories/${tId}/checkpoints`, params);
        })
      );
    }