在 Angular service.subscribe 中组件的构造函数中的更新不起作用

In Angular Update in Component's Constructor in service.subscribe doesn't work

我有两个组件,父组件和子组件,并使用共享服务在它们之间发送数据。

服务类如下所示:

export class AddItemDataTransferService {

  // Observable string sources
  private childData= new Subject<string>();
  private parentData= new Subject<string>();


  // Observable string streams
  childdata$ = this.childData.asObservable();
  parentdata$ = this.parentData.asObservable();

   // Service message commands
addChildData(ch: string) {
  this.childData.next(ch);
 }

 addParentData(ch: string) {
  this.parentData.next(ch);
  }

  }

使用 angular 文档中的教程,我做了一些事情并且在组件之间发送数据完美无缺。

让我们看看子组件的外观:

export class AddItemSuccesResultComponent implements OnInit {
  newString = "This Should be changed";

 constructor(private getDataService: AddItemDataTransferService) { 

 getDataService.parentdata$.subscribe(
  ch=> {
              alert(ch);        
           this.newString = ch;

      });
   }
  }

获取数据完美无缺 here.in 浏览器警报被调用并弹出 window 显示 "ch" string.So 这意味着数据是从服务导入的,但是this.newString 不更新。

当我想在子组件中做同样的事情时,当我从 child.but 的父视图中导入数据时,同样的情况发生了,它失败了

尝试将代码移至 ngOnInit。请注意您放入构造函数中的逻辑,因为可能依赖于该逻辑尚不可用。数据在构造函数中并不总是立即可用,因此它应该只将初始局部变量设置为简单值。 ngOnInit 是组件获取其初始数据的好地方;

在您的 class AddItemDataTransferService 中,您应该将 Subjects 更改为 BehaviorSubjects。我假设您的子组件在您的服务 之后订阅公开的可观察对象 addParentDataaddChildData

由于您正在使用 Subjects 一旦您向它们添加数据,它们将只向当前订阅者广播。任何后续订阅者都不会获得先前广播的数据。

通过使用 BehaviorSubject,任何后续订阅者都将获得之前广播的数据。

export class AddItemDataTransferService {

  // BehaviorSubjects must have a starting value. 
  private childData= new BehaviorSubject<string>(null);
  private parentData= new BehaviorSubject<string>(null);