@
@
@atmk2018-09-21 08:27:33
Angular
@atmk, 2018-09-21 08:27:33

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

1 answer(s)
D
Dmitry Eremin, 2018-09-21
@EreminD

when you hide, the 1st component is destroyed?
Add the OnDestroy interface to the component and implement the method

ngOnDestroy(): void {
   console.log('destroyed')
}

If it works, then I think you just need to unsubscribe when destroying
reactivex.io/rxjs/class/es6/Subscription.js~Subscr...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question