what i want to achieve:
I have two components that are not linked
- I want to set a variable's value from component1 and then use it in component2
- Component2 should get updated value if its changed in component1
My solution:
- Inject a service in both the components
- add an observable in that service
- set observable value from component1 and subscribe in component2
Problem in above solution:
The subscribe in component2 is not called when component1 value is updated, its only called at page loading.
Please see the code below:
service
export class HomeService {
public receiveMedOrderVisibleSubject: BehaviorSubject<any>;
public receiveMedOrderVisibleObservable: Observable<any>;
constructor() {
this.receiveMedOrderVisibleSubject = new BehaviorSubject<any>(
localStorage.getItem("RECEIVED_MED_ORDERS_COUNT")
);
this.receiveMedOrderVisibleObservable = this.receiveMedOrderVisibleSubject.asObservable();
this.receiveMedOrderVisibleSubject.subscribe(data => {
console.log("HomeService subscriber called" + data);
});
}
}
Component1
export class HomeComponent implements OnInit {
constructor(private homeService: HomeService) {}
ngOnInit() {
this.homeService.receiveMedOrderVisibleSubject.next(1);
}
setData() {
//endpoint will return the data that should be set in variable, and that endpoint is called when dropdown value is changed.
//I have removed that code for simplification
this.homeService.receiveMedOrderVisibleSubject.next(10);
}
}
component2
export class PageOneComponent implements OnInit {
constructor(private homeService: HomeService) {}
ngOnInit() {
this.homeService.receiveMedOrderVisibleSubject.subscribe(data => {
console.log("page-one subscriber called" + data);
//this is called only when page is loaded, it's not called when this.homeService.receiveMedOrderVisibleSubject.next(10); is executed from component1
});
}
}
How can I set the value in component1 and then use it in component2 when both components are not internally linked, you can say that component1 is header and component2 is loaded by active URL
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…