Angular,将选择器存储数据发送到子组件

Angular, send selector store data to child component

我想请教您有关从选择器、store - ngrx 向子组件发送数据的解决方案。

只有:

public testValue;

 this.store$.select(selectorDataTest).subscribe(
        data => {
          this.testValue = data;
        }
    );

并且在模板中只是:

<child-component [testValue] = "testValue"></child-component>

我考虑async等等

当您使用 select 从商店获取一些数据时,它作为 Observable 返回,(请在管道内使用 select)这就是您正确订阅 this.store$.pipe(select(selectorDataTest)) 的原因.

如果你记得退订,这个方法更好,我有两个方法给你:

1.
dataSubscription: Subscription;

ngOnInit() {
  this.dataSubscription = this.store$.pipe(select(selectorDataTest))
    .subscribe(data => this.testValue = data);
}

ngOnDestroy() {
  this.dataSubscription.unsubscribe();
}
2.
componentDestroyed$ = new Subject();

ngOnInit() {
  this.dataSubscription = this.store$
    .pipe(
      takeUntil(this.componentDestroyed$),
      select(selectorDataTest)
    )
    .subscribe(data => this.testValue = data);
}

ngOnDestroy() {
  this.dataSubscription.next();
  this.dataSubscription.unsubscribe();
}

在你的child-component里面你有

@Input() testValue: any;

所以你的方法

<child-component [testValue] = "testValue"></child-component>

也是正确的。

但是,如果您不想处理订阅,Angular 会为您提供 async 管道。
它接受一个 Observable 并为您订阅和取消订阅。这样你就可以只保留 Observable select returns 你,就像这样:

dataTest$: Observable<any>;

ngOnInit() {
  this.dataTest$ = this.store$.pipe(select(selectorDataTest));
}

和你的 parent.component.html

<child-component [testValue]="testData$ | async"></child-component>

而且,再一次,在你的child-component里面你有

@Input() testValue: any;