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.
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:
'Data Changed') using the code this.candidatesService.mySubject.next('Data Changed').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.
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