angular - 在输入更改和更新 View 时调用服务

标签 angular

我正在编写一个简单的组件,它将 Id 作为输入并调用服务方法来返回要显示的实体:

@Input() id: string;

ngOnInit(): void {
    if (this.id != undefined && this.id != "") {
        this.detailSubscription=this.service.load(this.id)
            .subscribe(result => {

                    this.detail$ = result;
                    this.cd.detectChanges();
            });
    }
}

ngOnDestroy() {
   this.cd.detach();
   this.detailSubscription.unsubscribe(); 
}

此组件仅在第一次时有效。如果输入 Id 更改,则不会更新 View 。

我还尝试将服务调用放在 onChanges 方法中,但由于取消订阅仅在 onDestroy 方法上调用一次,因此它不起作用。

如何实现这一目标?

最佳答案

您需要使用 ngOnChanges 而不是 ngOnInit ,如下所示。 ngOnInit 只会触发一次,而 ngOnChanges 将在每次输入值更改时触发。

并在调用服务之前尝试取消订阅。

 ngOnChanges(changes: SimpleChanges) {

   if (changes['id']) {
      if(this.detailSubscription) {
         this.detailSubscription.unsubscribe();
      }
      //call your service here
   }
}

关于angular - 在输入更改和更新 View 时调用服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44414974/

相关文章:

javascript - 在 Angular 的 innerHTML 中使用字符串插值

angular - 无法读取某些 cookie

angular - 在运行时以 Angular 关闭动画

angular - NullInjectorError : No provider for MediaMatcher

java - 将多个对象或列表对象从 Spring Boot 发送到 Angular

angular - 在调用构造函数或 ngOnInit 之前渲染的组件

"components should create "测试用例的 Angular 5 单元测试抛出错误

javascript - 窗口 :beforeunload works on chrome browser but not chrome mobile browser. Angular 6

validation - 使用 ngModel 验证 Angular 2 单选按钮

javascript - Angular 2 - 在 setTimeout 中使用 'this'