ngOnChanges not firing when attribute changed by Observable/subscrption

后端 未结 2 1721
隐瞒了意图╮
隐瞒了意图╮ 2021-01-20 14:49

I\'m trying to do something after an Observable/subscribe completes. I\'m changing an Input property in the subscribe( onNext )<

相关标签:
2条回答
  • 2021-01-20 15:19

    As stated by Günter it doesn't quite work like that from my understanding... When using Observables you can trigger a change manually with the Observable.next() feature. The trick here is that you will have to return an Observable from your service- this can be done like so:

    import {Observable, Subject} from "rxjs/Rx"; // remember the '/Rx', it got me...
    
    export class NamesService {
        private initialNames: Array<string> = ["Joe", "Jack", "Pete"];
    
        get(){
            let names: Subject<Array<string>> = new Subject<Array<string>>();
    
            names.next(this.initialNames);
            setTimeout(() => {
                this.initialNames.push('someOtherNames');
                names.next(this.initialNames);
            }, 1000);
            return names.asObservable();
        }
    }
    

    And then subscribe to it much as you have already done, and when the .next() runs it will trigger a change on the .subscribe() method.

    I would recommend splitting this up from the get method though, you could possible have your own onNameUpdate() method that return the observable array- or something like that.

    0 讨论(0)
  • 2021-01-20 15:25

    That's "as designed"

    ngOnChanges() is only called when change detection updates a binding to an @Input(). If the input is changed imperatively from somewhere then it isn't called.

    Just make names a getter/setter for code to be executed every time when the property is updated.

    0 讨论(0)
提交回复
热议问题