angular-httpangular2-observablesangular-http-interceptorsangular-httpclient-interceptors

Chain Two request and return an object Angular 7


I have a request to search the notifications that match with an user input search, but each notifications that match have a newsId properties, I want when I got the notification from server, make another request to search the news obj from the newsId properties and after return an obj with the notification obj and news obj

import { Notification } from './notification';
import { New } from './new';

export class NotificationEditResponse {
  notification:Notification;
  newsBelong?:New;
  error?:any;
}



export class EditNotificationsResolverService implements Resolve <NotificationEditResponse> {

  constructor(private notificationService:NotificationsService) { }

  return this.notificationService.getNotificationById(+id)
.pipe(
  flatMap(notificationObj=>{
    return this.newsService.getNewById(notificationObj.newsId)
    .pipe(
      map((res:New)=>({
        notification:notificationObj,
        newsBelong:res
      })),
    catchError(error=>{
    const msg=`Retrieval error : ${error}`;
    console.log(msg);
    return of({notification:null, error:msg,newsBelong:null});
  })
    )
  })
 );

}

}


Solution

  • it is better to use concatMap instead of flatMap because according to your use case this.newsService.getNewById should wait for this.notificationService.getNotificationById to emit a value.