angular - 当 Observable/订阅更改属性时 ngOnChanges 不触发

标签 angular angular2-services

我正在尝试在 Observable/subscribe 完成后做一些事情。我正在更改 subscribe( onNext ) 方法中的 Input 属性,但 ngOnChanges 从未触发。

我应该做些什么不同的事情?

import { Component, EventEmitter, 
  OnInit, AfterViewInit, OnChanges, SimpleChanges,
  Input, Output
} from '@angular/core';

@Component({
  templateUrl: 'myTemplate.html'
    , providers: [ NamesService ]
})

export class MyPage  {
  @Input() names: any[];

  constructor( public namesSvc: NamesService) {}

  ngOnInit() {
    this.getNames$()
  }


  getNames$() : void {
    this.nameService.get().subscribe( 
      (result)=>{
       this.names = result;
       console.log(`getNames$, names=${this.names}`);

       // I could doSomething() here, but it doesn't seem like the correct place
       // doSomething()  

      }
      , error =>  this.errorMessage = <any>error
    )
  }

  ngOnChanges(changes: SimpleChanges) : void {
    // changes.prop contains the old and the new value...
    console.warn(`>>> ngOnChanges triggered`)
    if (changes["names"]) {
      console.warn(`>>> ngOnChanges, names=${changes["names"]}`)
      this.doSomething()
    }
  }

  doSomething(){
    console.log("doing something");
  }
}

最佳答案

这是“按设计”

ngOnChanges() 仅在更改检测更新绑定(bind)到 @Input() 时调用。如果输入从某处强制更改,则不会调用它。

只需将 names 设置为每次属性更新时要执行的代码的 getter/setter。

关于angular - 当 Observable/订阅更改属性时 ngOnChanges 不触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39913255/

相关文章:

angular - ng2 从 HttpGet 服务获取对象

angular - 点击 linkedin 的 http get 请求,在 Angular 2 中给出错误

Angular ngx-bootstrap 崩溃不是动画

ios - Ionic 5 Google Map Marker 在 IOS 上打破动画

javascript - 错误类型错误 : Cannot read property 'city' of undefined

css - Angualar2和Stylelint : Unexpected unknown pseudo-class selector ":host"

angular - 为什么嵌套订阅不好?

angular - 如何在运行时更改 NgModule 配置

javascript - 在 Typescript 中的类方法中创建方法 - Angular 2

Angular 2 - 超时后取消订阅