Reputation: 1024
I have some service
isDocAdd: Subject<boolean> = new Subject<boolean>();
addDocument(header) {
return this.http.post(this.addHl7DocumentUrl, header)
.map((response: any) => { if (response.status === '404') {
this.isDocAdd.next(true);
}
else {
this.isDocAdd.next(false);
}
return response;
})
.catch((error: Error) => {
console.error('Error:', error);
return Promise.reject(error.message || error);
});
}
and In component.ts subscribe() notification
subscription: Subscription;
message;
constructor(private documentService: DocumentService) {
this.subscription = this.documentService.isDocAdd.subscribe(val => { this.message = val; });
}
In method addDocument() this.isDocAdd.next(val) is set but don't notify component about changes and subscribe() method does not execute.
Upvotes: 0
Views: 83
Reputation:
This is because your component is created after your service.
This means, your subject is not known by your component, so you call next while nothing has subscribed.
One solution is to use a BehaviorSubject
instead :
isDocAdd: BehaviorSubject<boolean> = new BehaviorSubject<boolean>();
It works exactly the same, but a BehaviorSubject
will notify its observers when you instanciate them (even if the value is null, so test that !)
Upvotes: 2
Reputation: 804
private isDocAdd= new Subject<boolean>();
isDocAdd$ = this.isDocAdd.asObservable();
addDocument(header) {
return this.http.post(this.addHl7DocumentUrl, header)
.map((response: any) => { response.status === '404') {
this.isDocAdd.next(true);
}
else {
this.isDocAdd.next(false);
}
return response;
})
.catch((error: Error) => {
console.error('Error:', error);
return Promise.reject(error.message || error);
});
}
and in component.ts
subscription: Subscription;
message;
constructor(private documentService: DocumentService) {
this.subscription = this.documentService.isDocAdd$.subscribe(val => { this.message = val; });
}
Upvotes: 1
Reputation: 41445
Need to create an observable from your subject in order to subscribe to it. use asObservable
isDocAdd: Subject<boolean> = new Subject<boolean>();
onChanged: Observable<boolean> = this.isDocAdd.asObservable();
Now subscribe to the onChanged
this.subscription = this.documentService.onChanged.subscribe(val => { this.message = val; });
Upvotes: 0