Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 communicating between components through service

i am working on an Angular 5 application and i have an API that store my data. The thing is i have two components, one for displaying data and one for posting data.

They both interact with the API through a service with two functions:

addCandidate(candidate: Candidate): Observable<Candidate> {
  this.candidatesList.next(this.http.get(this.apiUrl));
  return this.http.post<Candidate>(this.apiUrl, candidate, httpOptions);
} 

listCandidates(): Observable<Candidate[]> {
  return this.http.get(this.apiUrl).map(res => <Candidate[]>res);
}

The components have methods for subscribing to the service:

saveCandidate(): void {
  if(this.candidate.skills.indexOf(', ') >= 0) {
    this.candidate.skills = (<string>this.candidate.skills).split(', '); 
  }
  this.candidatesService.addCandidate(this.candidate).subscribe();
}

And respectively ( this one is on init ) :

ngOnInit() {
  this.candidatesService.listCandidates().subscribe(candidates => this.candidates = candidates);
}

So, hence i can't really know when the api is updated, i want to update the list after saveCandidate() method takes action.

How does one update one component with new api data after another submitted to the servic?.

Side note: i tried using rxjs Subject.asObservable().next(..the http request). But Observable.next is not a method. Maybe i misused them.

like image 503
Gabriel Avatar asked May 19 '26 07:05

Gabriel


1 Answers

The method you tried (i.e, Subject) is the correct way to approach this problem.

Use this link for improving your understanding on Subject and follow these points:

  1. Declare the subject in the service
  2. In the component where you are posting data, make the subject emit an event with a string value (let's say, 'Data Changed') using the code this.candidatesService.mySubject.next('Data Changed').
  3. Subscribe to this Subject in the component where you are listing the data and call your service method to get your data inside the subscribe method like this:

    this.candidatesService.mySubject.subscribe((value) => { this.candidatesService.listCandidates().subscribe(candidates => this.candidates = candidates); });

    This should solve your problem.

like image 137
Arjun Panicker Avatar answered May 22 '26 14:05

Arjun Panicker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!