Listen to Restfull API consumer data updates from Angular 5

3

I am new to Angular, to explain myself properly I will share an example.
When we have installed the Firebase library in our project, we can call the information in 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 takes care of listening to any changes in the database and updating them in the user view without having to refresh it (this is done by making a manual change on a certain field in the same Firebase database).

So, in what way can this result be achieved, if for example I am consuming an API Rest? If by 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;
  });
}
    
asked by bitquipu 11.09.2018 в 05:19
source

1 answer

0

I'm not sure how valueChanges () is implemented, if you create a webSocket to receive push notifications or simply make an AJAX call every X seconds, but if you have a REST API, the path is the second option:

import { timer } from 'rxjs/observable/timer';
const TIME=5000; //milisegundos
export class UserService {

  ...

  get():Observable<User[]>{
    return this.httpClient.get<User[]>(this.API_ENDPOINT+'/users_location');
  }

  pollUsers(): Observable<User[]> {
        return timer(0,TIME).switchMap(() => this.get());
    }
}

What this code does: the pollUsers method returns an observable that every 5 seconds will make an AJAX call to the server and issue the response. This is an example that demonstrates the power of the Observables regarding the promises: the observable continues to work until we do a unsuscribe , it will periodically continue to send data without having to do anything else.

The timer(X,TIME) function does the following: it issues a sequence of numbers, starting with 0. It does so every TIME milliseconds, waiting X milliseconds for the first emission. As this value does not help us at all, with switchMap we change it for something else: the result of calling this.get() .

PS: REST and WebSockets are not exclusive, REST is an architectural style, not a technology. Nothing prevents you from having a URL RESTful that would allow a connection through the WebSocket protocol so that it is the server that emits the changes in real time. My solution assumes that you do not want / can change the backend API

    
answered by 11.09.2018 / 09:35
source