I am new to Angular RXJS, I am trying to add the post to the server, and then get all posts from the server because I am using Server-side pagination.
Could you please let me know why the addPostToServer function is called but the HTTP Post is not! or if you have a better approach to achieve the same?
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
})
);
}
CodePudding user response:
The HTTPClient will not make a call to the server until you subscribe to the Observable, so call to addPostToServer won't send the HTTP request.
You can subscribe to the observable
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
});
}
Or convert it to a promise using lastResultFrom if using RxJs 7 the use async/await
async addPostToServer(post: Post | string) {
let result = await lastResultFrom(this.http.post<APIResponse<Post>>(
this.APIURL '/posts/',
post
));
}
Or use toPromise is using RxJs 6
async addPostToServer(post: Post | string) {
let result = await this.http.post<APIResponse<Post>>(
this.APIURL '/posts/',
post
).toPromise();
}