I am new to Angular, to explain myself properly I am going to start from an example.
When we have the Firebase library installed in our project, we can call the information from the Users table as follows:
constructor(db:AngularFirestore){
db.collection('Users').valueChanges().subscribe((data: User[]) => {
this.users= data;
console.log(this.users);
});
}
The valueChanges() method is responsible for listening to any changes in the database and updating them in the user view without the need to refresh it (this is when making a manual change on a certain field in the same Firebase database).
So, how can this result be achieved, if for example I am consuming an API Rest? If when making a direct change in the database, this change is reflected in the user's view without the need to refresh.
// users.service.ts
get():Observable<any>{
return this.httpClient.get(this.API_ENDPOINT+'/users_location');
}
// user.component.ts
users: Users[]=[];
constructor(private userService: UsersService) {
this.getTrailers();
}
getUsers(){
this.userService.get().subscribe( (data:Users[])=>{
this.users= data;
});
}
I'm not sure how valueChanges() is implemented, whether it creates a webSocket to receive push notifications or just makes an AJAX call every X seconds, but if you have a REST API, the way is the second option:
What this code does: The method
pollUsers
returns an observable that every 5 seconds will make an AJAX call to the server and emit the response. This is an example that demonstrates the power of Observables regarding promises: the observable continues to function until we do aunsuscribe
, it will periodically continue to emit data without us having to do anything else.The function
timer(X,TIME)
does the following: it outputs a sequence of numbers, starting with 0. It does this everyTIME
millisecond, waitingX
milliseconds for the first output. Since that value is of no use to us,switchMap
we change it to something else: the result of callingthis.get()
.PS: REST and WebSockets are not mutually exclusive, REST is an architectural style, not a technology. Nothing prevents you from having a RESTful URL that allows a connection through the WebSocket protocol so that the server is the one that emits the changes in real time. My solution assumes you don't want/can't change the backend API