【问题标题】:RxJS Angular - Pass object's property of Observable as ObservableRxJS Angular - 将 Observable 的对象属性作为 Observable 传递
【发布时间】:2021-06-11 08:40:38
【问题描述】:

我有 Observable,里面包含大对象。我只想将一个属性作为可观察的传递给子组件。 我可以通过管道输入组件,但我需要为它再创建一个可观察的。 我可以在html里面做吗?

// this is service;
this.theObject$ = new BehaviourSubject<TheObject>(null);
this.theObject = {...alot, 
    title as string,
    neededValue as number
};
this.theObject$.next(theObject);

get getTheObject (): Observable<TheObject> {
   return this.theObject as Observable;
}

// component:
theObject: Observable<TheObject>;
ngOnInit(){
this.theObject = this.service.getTheObject;
}

// component html:
<div>
<span>{{(theObject | async).title}}</span>
<app-custom-component [neededValue$]="(theObject | async)?.neededValue"></app-custom-component>
</div>

//Custom Component
some: number;
@Input()'neededValue': Observable<number>;
ngOnInit(){
  this.neededValue.subscribe(res => {
    this.some = res;
  })
}

我在这里遇到了一个错误:

错误类型错误:无法读取未定义的属性“订阅”

我认为问题出在:(theObject | async)?.neededValue。有没有办法在没有额外可观察的情况下解决这个问题? 此外,我不会将所有大对象传递给自定义组件。

【问题讨论】:

  • 模板和控制器的变量名不一致(neededValue$ vs neededValue)。
  • 我不会将所有大对象传递给自定义组件 - 您可以使用管道/映射来提取属性 => public neededValue$ = this.service.getTheObject().pipe(map(o =&gt; o.neededValue)); 然后在您的模板如[neededValue]="neededValue$ | async"

标签: angular typescript rxjs


【解决方案1】:

如果你只想传递 BehaviorSubject 值,为什么不使用 asObservable() 方法

  theObject             = new BehaviorSubject<TheObject>(null);

  // This obs will contain the entire object
  theObject$            = this.theObject.asObservable();

  // This obs will contain only neededValue
  theObjectNeededValue$ = this.theObject.asObservable().pipe(pluck('neededValue'));

在组件内部只需分配服务可观察变量并将它们与async 管道一起使用,或者如果您想将它们作为可观察的传递给子组件。

// component.ts
theObject$ = this.service.theObject$;
theObjectNeededValue$ = this.service.theObjectNeededValue$;

// component html:
<div>
<span>{{(theObject$ | async).title}}</span>
<app-custom-component [neededValue$]="theObjectNeededValue$"></app-custom-component>
</div>

【讨论】:

  • 我只是想让我的代码更优雅,而不是订阅 2 个 observables
  • 好吧,有了额外的 observable,其底层数据源仍然是 BehaviorObject 的值,您将能够以更好的方式管理应用程序。不确定这里的用例,但是如果您只想根据需要的真实值显示自定义组件,那么只使用一个 observable 会使其更加混乱。
猜你喜欢
  • 2021-12-20
  • 1970-01-01
  • 2019-06-09
  • 2021-05-24
  • 2019-04-05
  • 2021-11-26
  • 2021-10-27
  • 2023-03-23
  • 1970-01-01
相关资源
最近更新 更多