Answer the question
In order to leave comments, you need to log in
Why does subscription to Observeble (Subject) variable disappear in Angular?
The varServ$ variable is created in the service. Its value is set from outside via setVar() (can be set from any component).
export class MyService {
varServ$ = new Subject();
}
setVar(sss: number){
this.varServ$.next(sss);
}
In the first component I subscribe to this variable (on varServ$), I
display it in the form.
Everything works here. When varServ$ is changed from outside, varComp1 is changed and the mapping of varComp1 is changed.
export class MyComponent1 implements OnInit {
varComp1: number;
constructor(
private myService: MyService,
) { }
ngOnInit() {
this.myService.varServ$.subscribe(x => this.varComp1 = x);
}
HTML:
Variable - {{varComp1}}
I need to show and hide the first component in the second component.
export class MyComponent2 implements OnInit {
viewForm=true;
}
HTML:
Show
Hide
PROBLEM AND QUESTION.
When the second (and in it the first) component is initially displayed, the varComp1 variable is displayed.
But, if (in the second component) HIDE and SHOW the first component again, then the varComp1 variable of the first component disappears.
Why does the value of the first component varComp1 disappear if there is a subscription in the first component to varServ$ and the value of varServ$ was previously set and did not change.
If you set the value of varServ$ on a new (from the outside) (via next), then varComp1 will naturally appear, and when hidden / shown it disappears again.
Answer the question
In order to leave comments, you need to log in
when you hide, the 1st component is destroyed?
Add the OnDestroy interface to the component and implement the method
ngOnDestroy(): void {
console.log('destroyed')
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question