Angular 6 Data Sharing Service Subscribe not triggered
You could effectively use
Subject
along with the router. So, Here is a live solution for your scenario usingRouter
&Subject
.
Your service will simply contain -
public setValue(value: string): void {
this.valueObs.next(value);
}
public getValue(): Observable < string > {
return this.valueObs;
}
Then, your ComponentB
will contain -
buttonClick() {
this.socialService.setValue("linked successfully");
this.router.navigate(['/a']);
}
And, your ComponentA
's constructor will contain -
this.socialService.getValue().subscribe(data => {
this.dataFromB = data;
console.log('Trigger from ComponentB');
console.log(data);
})
I think you would need a ReplaySubject for that. Your component subscribing to the observable subscribes, after the value was emitted and hence the observable doesn't emit again, there is no value to get from that observable. A ReplaySubject takes care of giving the subscriber every emits which have taken place even before the subscription is done.
@Tushar Walzade solution works, because both components are within the app-component, so both observers are subscribing before the event was emitted. (The subscription takes place inside the constructor for both components, which is called before you click the button). But if you have a lazy loaded module for example, the one component would be created only on loading and then you would only get the data if you use a ReplaySubject or the rxjs operator publish or share
Have a look here:
publish and share operators subjects, behavior subjects and replay subjects