0
votes

I am passing some @Input props down from the parent and whenever my prop is updated, I want my component to update.

What I was doing is this:

@Input() variable;
@Input() variable2;

public deets;

constructor() { 
  this.details$ = this._sore.select("details") 
}

ngOnInit() { }

ngOnChanges(changes: SimpleChanges) {
  if (
    changes.variable && changes.variable.currentValue ||
    changes.variable2 && changes.variable2.currentValue
  ) {
    this.apiCall();
    this.subscribeMethod();
  }
}

ngOnDestroy() {
  this.deets.unsubscribe();
}

subscribeMethod() {
  this.deets = this.details$.subscribe(value => {
    if (value) // this.action1()
  }
}

apiCall() {
  this._store.dispatch(new LoadDetailsAction);
}

action1() { console.log("test") }

However what I noticed, is that when I make a change in my Input prop from the parent and that is updated, I am making my API call once (good) and but then it looks like I am subscribing again ?? so I am having some sort of memory leak.

If in my this.action1() I make a console log, the first time around, it will log once. then if I update my variable or variable2 again, it console logs twice. then thrice. etc.

Is it because my subscription isn't being deleted? So it's calling action1 in multiple subscriptions?

I thought my ngOnDestroy() would take care of that but I guess since the component isn't actually being destroyed but updated, that isn't taking care of it.

So would I move my subscribeMethod to onInit? into my constructor? How do I avoid these excess actions?

Thanks!

Edit I tried moving my subscribeMethod to my ngOnInit and it seems like it fixed the problem, but it is giving me a console log twice. Once with the old subscribe data, once with the new :(

1

1 Answers

0
votes

First thing. Angular will automatically call ngOnChanges any time one of your inputs change, so you can remove all the code revolving around simpleChanges. Generally, you would use code like that if you had some conditional logic regarding to specific inputs. In your case, your condition is true if any input changes, so you can just remove that logic altogether.

Second, you're on the right track with your idea of setting your subscription inside ngOnInit. You can have something like this:

this.deets = this._store.select("details").subscribe(value => {
    if (value) // this.action1()
}

I am not sure what you mean with your edit. By definition, you are expecting to call subscribe if the value of your observable changes. Perhaps you can clarify and I'll edit my response.