I have two different components
first.component.ts
ngOnInit(): void {
}
setStatusOfUser(){
this.Service.setStatus(Id,userId).subscribe((data)=>{
this.msg=data;
})
}
second.component.ts
ngOnInit():void {
this.getProgress()
}
getProgress(){
this.service1.getProgress().subscribe(data=>{
this.progresss=data;
});
}
when I am refrshing the page its working but when clicking on the setStatusofUser I want to render the get progress method in another component how to do that.
CodePudding user response:
first.component.ts
You can use ViewChild Annotation to call a method in another component
@ViewChild(SecondComponent) secondComponent!: SecondComponent;
setStatusOfUser(){
this.secondComponent.getProgress();
}
CodePudding user response:
The reason why it works only on refresh because you call getProgress() only once onInit(). One possible solution that you can use is to use a service to share info between components.
Service
private statusObs = new BehaviorSubject<any>(null);
setStatus(data: any) {
this.statusObs.next(data);
}
getStatus() {
return this.statusObs;
}
First Component
constructor(private communicationService:<YourServiceName>){}
ngOnInit(): void {
}
setStatusOfUser(){
this.Service.setStatus(Id,userId).subscribe((data)=>{
this.communicationService.setStatus(data); // Pass data to the service
this.msg=data;
});
}
Second Component
constructor(private communicationService:<YourServiceName>){}
ngOnInit():void {
this.communicationService.getStatus().subscribe( status => {
// We used BehaviorSubject<any>(null) with initial value null
// so use this null check to avoid calling getProcess() in the beggining
if (status !== null) { // check if your data is the data you want
this.getProgress();
}
});
}
getProgress(){
this.service1.getProgress().subscribe(data=>{
this.progresss=data;
});
}
