简体   繁体   中英

Catching error in Angular 9 with catchError operator

Hi I try to catch error and send information about log with using Rxjs operator catchError. Below I show function used in my post service responsible for fetching some data:

fetchPosts() {
    const  url = 'some url';
    return this.http.get<{ [key: string]: Post }>(url)
      .pipe(
        map((responseData) => {
            const postArray: Post[] = [];
            for (const key in responseData) {
              if (responseData.hasOwnProperty(key)) {
                postArray.push({...responseData[key], id: key});
              }
            }
            return postArray;
          }, catchError(errorResponse => {
              // now we can send for example information to analytic serv
          this.logService.addNewLog(errorResponse.message);
          return throwError(errorResponse.message);
          })
        ));
  }

The problem is it dosen't work with map operator. When I delete map operator it will work correctly. Like below:

fetchPosts() {
    const  url = 'some url';
    return this.http.get<{ [key: string]: Post }>(url)
      .pipe(catchError(errorResponse => {
          this.logService.addNewLog(errorResponse.message);
          return throwError(errorResponse.message);
          })
        );
  }

How can I solve this problem? I wish it would work with those 2 operators: map, catchError. What is wrong with my code? I would be greateful for help.

Operators must be piped in individually. At the moment you're piping in the catchError inside the map operator. Try the following

fetchPosts() {
  const  url = 'some url';
  return this.http.get<{ [key: string]: Post }>(
    'https://http-request-learning.firebaseio.com/posts.json'
  ).pipe(
    map((responseData) => {
      const postArray: Post[] = [];
      for (const key in responseData) {
        if (responseData.hasOwnProperty(key)) {
          postArray.push({...responseData[key], id: key});
        }
      }
      return postArray;
    }),              // <-- close `map` here
    catchError(errorResponse => {
      // now we can send for example information to analytic serv
      this.logService.addNewLog("sss");
      return throwError(errorResponse.message);
    })
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM