Hi i'am new to Angular 6 and can't make things work after several researching. I have a list coming from jsonplaceholder.typecode.com and as i have read its docs, I can post, delete, and update but how can i make my list change async'ly as i perform those methods.
this are my methods from a service
getContacts(){
return this.contact = 
 this.http.get('https://jsonplaceholder.typicode.com/users');
}
getUser(id){
 return this.http.get('https://jsonplaceholder.typicode.com/users/'+id);
}
addContact(newContact: Contact){
 return this.http.post('https://jsonplaceholder.typicode.com/users', 
newContact);
 }
 removeContact(contact){
  return 
 this.http.delete('https://jsonplaceholder.typicode.com/users/'+contact.id);
}
updateContact(contac: Contact){
return 
this.http.put('https://jsonplaceholder.typicode.com/users/'+contac.id, 
 contac);
 } 
                Start by creating a BehaviorSubject in your service : 
contacts$ = new BehaviorSubject([]);
This creates a proxy (Observable + Observer) that you can subscribe & listen to.
Now that we have that, let's populate it :
getContacts() {
  this.http.get(url).subscribe(contacts => this.contacts$.next(contacts));
}
With this code, you get the list of contacts and push it into your proxy.
addContact(newContact: Contact){
  this.contacts$.pipe(
    take(1),
    switchMap(contacts => this.http.post(url, newContact).pipe(
      map(() => [...contacts, newContact])
    )),
  ).subscribe(contacts => this.contacts$.next(contacts));
}
With this one, you create a new contact and append it to your list of existing contacts.
By creating a proxy, you create a datasource, that you handle with your HTTP calls.
For instance, in the first method, I emit a value that is the array of contacts. Every listener (i.e. everywhere you have written this.myService.contacts$.subscribe) will receive this value. 
In the second one, I start be getting the list of contacts and listen to a single event (i.e. future calls to contacts$.next won't do anything to this subscription). Then, I request a contact creation, and once done, I create a new datasource containing the previous contacts, plus the new contact, and then emit an event.
This isn't very clear and it can seem exhausting to learn, but once you can use it, it becomes very powerful.
Now that you have the basics, I'll let you handle update and delete, because I'm not here to code for you !
And if you have any issues with thise code, then I suggest you read the documentation and make several tutorials about RxJS, because really, this is very powerful, and you almost always use it with Angular.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With