Angular 6 : Real time data
Your code is good but unfortunately a Promise only resolves to one value.
However, observables can provide you with a real time stream of data!
Make the moviesService.getComments() method return an observable which returns comments.
It should look a little something like this (assume you are using the angular HttpClient to fetch the comments):
// movieService.service.ts
import { HttpClient } from '@angular/common/http'
...
constructor(
private http: HttpClient
)
getComments() {
return this.http.get<Comments>(url)
}
...
You can consume the observable like so:
// comment.component.ts
...
comments: Observable<Comments>
...
ngOnInit() {
this.comments = this.movieService.getComments()
}
...
And finally in the template:
// comments.component.html
<div *ngFor="let comment of comments | async" class="col-md-7">
<ul class="list-group">
<li class="list-group-item">Author: {{comment.author}}</li>
<li class="list-group-item">Comments: {{comment.description}}</li>
</ul>
<br>
</div>
The Dead Man
Updated on June 04, 2022Comments
-
The Dead Man almost 2 years
I have app in which a user can add a comment , and the comment is displayed , my problem is comments are not displayed untill I refresh the page.
I want a comment to be displayed after the user click just enter or submit button
Here is what I have so far:
Getting data service.ts
this.activeRouter.params.subscribe((params) => { let id = params['id']; this.moviesService.getComments(id) .then(comments => { console.log(comments); this.comments = comments; }); });
2.Then display to the front end: html
<div *ngFor="let comment of comments" class="col-md-7"> <ul class="list-group"> <li class="list-group-item">Author: {{comment.author}}</li> <li class="list-group-item">Comments: {{comment.description}}</li> </ul> <br> </div>
Unfortunately when my server updates the JSON, the html does not update at all until I refresh the page then I can see the added comments wrong
what am I missing in my code to accomplish what I want? newbie though
-
The Dead Man almost 6 yearsHii @mateja so in which scenario we should consider using promise ?
-
Mateja Petrovic almost 6 yearsThe cool thing about observables is that they are so versatile. You can use them to work with streams of data or a single value, be it synchronous or asynchronous. That's why I tend to use observables and rxjs all the time. But if you
-
Mateja Petrovic almost 6 yearsAlas, but if you just want to get a single value and not a stream it's just fine to use a promise. There are so any great resources on this topic like stackoverflow.com/questions/37364973/promise-vs-observable and a side by side comparison youtube.com/watch?v=jgWnccjXR4I