[Fixed] RxJs map operator

Issue

I don’t understand how to solve an issue in the following scenario:

getPosts(): Observable<Post[]> {
    return this.http.get<Post[]>(this.postsUrl).pipe(
      tap(() => console.log('fetched posts')),
      catchError(this.handleError<Post[]>('getPosts', []))
    );
  }

…….

export const mapYearWeek = (post: Post): Post => {
  post.time = `
  ${moment(parseInt(post.time)).year()}
  -${moment(parseInt(post.time)).week()}
  `;
  return post;
};

………

ngOnInit(): void {
    this.postService
      .getPosts()
      .pipe(
        mergeMap(res => res.map(mapYearWeek(post: Post))),  
        tap((res) => console.log(res)),
        groupBy((post: Post) => post.time),
        mergeMap((group) => group.pipe(toArray())),
        tap((res) => console.log(res))
      )
      .subscribe();
  }

I’m getting error with mapYearweek func:

Argument of type ‘Post’ is not assignable to parameter of type
‘(value: Post, index: number, array: Post[]) => unknown’. Type
‘Post’ provides no match for the signature ‘(value: Post, index:
number, array: Post[]): unknown’.ts(2345)

Solution

  mergeMap(res => res.map(mapYearWeek(post: Post))),  

should be

  mergeMap(res => res.map(post => mapYearWeek(post))),  

Leave a Reply

(*) Required, Your email will not be published