Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
128
rated 0 times [  135] [ 7]  / answers: 1 / hits: 15110  / 5 Years ago, mon, november 4, 2019, 12:00:00

In my application there is a table that get rows from database.



This is the AJAX CALL (SERVICE)



getPosts(): Observable<Posts[]> {
return this.http.post<Posts[]>(this.myAppUrl + this.myApiPostsUrl, this.authService.getLoggedUserFromSessionStorage())
.pipe(
retry(1),
catchError(this.errorHandler)
);
}


All work perfectly, but my datas dont update automatically, and the user need to refresh the page to see the new rows, how can i do this?
I would like do that the new rows are added in the table dynamically ... without update the page.
This is the table



COMPONENT HTML



    <table *ngIf=(posts$ | async)?.length>0 class=table align-items-center table-flush>
.....
<tr *ngFor=let post of (posts$ | async) | filter:authService.filter | paginate: config | orderBy: key : reverse>
<!-- <td>{{posts.id}}</td>-->
<td>{{post.title}}</td>
<td>{{post.body}}</td>
.....
</table>


COMPONENT TS



ngOnInit() {
this.loadPosts();
}

loadPosts() {
this.message = 'Loading....';
this.posts$ = this.postService.getPosts();
if (this.posts$ == null) {
this.message = 'No Posts found';
}
}


Thanks so much.


More From » ajax

 Answers
30

There are several options. Here is a reactive way of handling this. Any time getPosts is successful, you'll need to refetch the initial data.



To fetch your initial data you will need to wrap your posts$ observable in an action stream:



// create a stream for your post request
private readonly postAction$ = new Subject();

posts$ = this.postAction$.pipe(
startWith(''),
concatMap(()=> {
return this.postService.getPosts(); // this will be your http get request
}),
)


The startWith operator will cause your get request to fire initially without an observable been passed to your postAction observable.



Your getPosts method now will call this.postAction$.next() on success, that will trigger the refetch of your posts$ observable.



getPosts(): Observable<Posts[]> {
return this.http.post<Posts[]>(this.myAppUrl + this.myApiPostsUrl, this.authService.getLoggedUserFromSessionStorage())
.pipe(
retry(1),
catchError(this.errorHandler),
tap(() => this.postAction$.next())
);
}


You can see a demo of this. Check the console, you'll see that the get request is fired every time the button is clicked.






With Interval



posts$ = interval(30000)
.pipe(
startWith(''),
switchMap(() => return this.postService.getPosts();)
)


Interval demo


[#51515] Thursday, October 24, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
susanap

Total Points: 413
Total Questions: 82
Total Answers: 99

Location: South Georgia
Member since Mon, Oct 19, 2020
4 Years ago
;