@karvanj wrote:
Hi all, with events being deprecated I am working through the use of observables. Taking some inspiration from this post I have implemented an observable to retrieve contacts via an HTTP service.
httpService.ts
getContactsHttp(params: any) { let headers: any = new HttpHeaders(this.authService.getHeadersClient()); return this.httpClient.get<ContactSearch[]>('/contacts', {headers: headers, params: params}); }
I then have a contact service which makes the actual calls and stores the response in a Behaviour Subject
contacts$
.contactService.ts
contacts$ = new BehaviorSubject<ContactSearch[] | null>(null); refreshContacts(params: any) { this.httpService.getContactsHttp(params).subscribe((data:ContactSearch[])=>{ this.contacts$.next(data); }); }
directory.ts
In my component I retrieve contacts on init.contacts$: Observable<ContactSearch[]>; constructor() { this.contacts$ = this.contactService.contacts$; } ngOnInit(){ this.contactService.refreshContacts(""); }
I also have another component which updates a contact then calls refreshContacts which then refreshes contacts in the directory component.
Based on this I have 2 questions:
Question 1
In refreshContacts() do I need to unsubscribe from the http call?Question 2
Is there are better way to do refreshContacts in the contact service? ie rather than subscribing are there alternate ways to emit next value when when http response is received?
Posts: 1
Participants: 1