首页 > 解决方案 > .subscribe() 方法中所做的更改未反映在它或模板中

问题描述

我正在使用主题向基本电话簿应用程序添加编辑功能。我在订阅回调内部对组件类变量所做的更改不会反映在它或模板中。

我已经尝试了以下问题的答案中列出的解决方案: Angular 2 View will not update after variable change in subscribe

在 service.ts 中:

startedEditing= new Subject<number>();

在 details.component.ts(数据在 fu 上传递的地方):

onEdit(){
    this.contactsService.startedEditing.next(this.id);
  }

在 edit-component.ts(在 ngOnInit 中):

this.subscription=this.contactsService.startedEditing.subscribe(
      (index:number)=>{
        this.editMode=true; 
        this.editedItemIndex=index;
        this.editItem=this.contactsService.getContact(this.editedItemIndex);         
          this.editForm.setValue({
            address:this.editItem.address,
            name: this.editItem.name,
            phone:this.editItem.phone,
            profession:this.editItem.profession
          });
          console.log("in subscribe: "+this.editedItemIndex);

      }
    );
    console.log("out of it :" + this.editedItemIndex);
  }

控制台上的输出:

in subscribe: 0
out of it : undefined

预期结果:

in subscribe: 0
out of it :0

标签: angularobservablerxjs6subject-observer

解决方案


his.editedItemIndext未定义是正常的console.log("out of it :" + this.editedItemIndex); 。这部分上面的代码是异步的,所以当console.log("out of it :" + this.editedItemIndex);运行时,订阅里面的代码还没有执行,this.editedItemIndex也没有初始化。现在,ngOnInit这是在您的组件中调用的第一个方法,因此在其他方法或模板中,this.editedItemIndex应该已经初始化并且不是未定义的。可能您可以共享您的 html 代码或其他未定义的地方,以便答案更准确。


推荐阅读