Angular RXJS调用http post request不起作用



我是Angular RXJS的新手,我试图将帖子添加到服务器,然后从服务器获取所有帖子,因为我使用服务器端分页。

你能让我知道为什么addPostToServer函数被调用,但HTTP Post没有!或者如果你有更好的方法来达到同样的效果?

Thanks in advance


private pageIndexSubject = new BehaviorSubject<number>(1);
public pageIndexAction$ = this.pageIndexSubject.asObservable();
private pageSizeSubject = new BehaviorSubject<number>(6);
public pageSizeAction$ = this.pageSizeSubject.asObservable();
private postInsertedSubject = new Subject<Post>();
postInsertedAction$ = this.postInsertedSubject.asObservable();
paginatedPosts$ = combineLatest([
this.pageSizeAction$, 
this.pageIndexAction$, 
this.postInsertedAction$.pipe(
startWith(''),
tap((post) => {
let m = this.addPostToServer(post).pipe(tap(res=>console.log('add post to server', res)))
})), 
]).pipe(
switchMap(([pageSize,pageIndex,post]) => 
this.http.get<APIResponse<PagedPosts<Post[]>>>(this.APIURL + '/posts', {
params:
{
size: pageSize.toString(),
page: pageIndex.toString()
}
})
.pipe(
map((response) => {
return response.data;
}),
catchError(this.handleError),
))
).pipe(shareReplay(1))

addPost(post:Post){
this.postInsertedSubject.next(post);
}
addPostToServer(post: Post | string) {
console.log('Function called but the HTTP is not !')
return this.http.post<APIResponse<Post>>(
this.APIURL + '/posts/',
post
)
.pipe(
map((res) => {
//not working
})
);
}

在你订阅Observable之前,HTTPClient不会调用服务器,所以调用addPostToServer不会发送HTTP请求。

你可以订阅可观察对象


addPostToServer(post: Post | string) {
console.log('Function called but the HTTP is not !')
return this.http.post<APIResponse<Post>>(
this.APIURL + '/posts/',
post
)
.subscribe((res) => {
// get Your result here
});
}

或者使用lastResultFrom将其转换为承诺如果使用RxJs 7使用async/await

async addPostToServer(post: Post | string) { 
let result = await lastResultFrom(this.http.post<APIResponse<Post>>(
this.APIURL + '/posts/',
post
));
}

或者使用toPromise是使用RxJs 6

async addPostToServer(post: Post | string) { 
let result = await this.http.post<APIResponse<Post>>(
this.APIURL + '/posts/',
post
).toPromise();
}

最新更新