RxJs 地图运算符
RxJs map operator
我不明白如何解决以下场景中的问题:
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();
}
我在使用 mapYearweek 函数时遇到错误:
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)
mergeMap(res => res.map(mapYearWeek(post: Post))),
应该是
mergeMap(res => res.map(post => mapYearWeek(post))),
我不明白如何解决以下场景中的问题:
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();
}
我在使用 mapYearweek 函数时遇到错误:
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)
mergeMap(res => res.map(mapYearWeek(post: Post))),
应该是
mergeMap(res => res.map(post => mapYearWeek(post))),