简体   繁体   English

无法通过 BehaviorSubject 访问数据的属性。 BehaviorSubject 上不存在属性

[英]Unable to access property of data through BehaviorSubject. Property does not exist on BehaviorSubject

While using BehaviourSubject to set shared data across my application, I am unable to access the properties of the data.使用 BehaviourSubject 在我的应用程序中设置共享数据时,我无法访问数据的属性。 Getting error :-获取错误:-

** **

property does not exist on type 'BehaviourSubject' 'BehaviourSubject' 类型不存在属性

** **

SharedService.ts共享服务.ts

setCommonData(data): void {
  this.commonData.next(data);
}
getCommonData(): Observable<BehaviorSubject<any>> {
  return this.commonData;
}

app.component.ts app.component.ts

// result = {id: number, name: string, info: {}}
getData(): void {
    this.dataService.getApi(url, {}, true).subscribe((result) => {
        this.sharedService.setCommonData(result);
    }
}

child.component.ts子组件.ts

displayData(): void {
    this.sharedService.getCommonData().subscribe((data) => {
         this.displatData = data // works
         this.info = data.info // property info does not exist on type 'BehaviourSubject<any>'
    });
}

You're returning an observable of the BehaviorSubject .您正在返回BehaviorSubject的可观察对象。 Instead you need to return the BehaviorSubject as an observable.相反,您需要将BehaviorSubject作为可观察对象返回。

Try the following尝试以下

setCommonData(data): void {
  this.commonData.next(data);
}

getCommonData(): Observable<any> {         // <-- return `Observable` here
  return this.commonData.asObservable();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 属性&#39;onNext&#39;在&#39;BehaviorSubject类型上不存在 <Filer> “ - Property 'onNext' does not exist on type 'BehaviorSubject<Filer>' TS2339:“行为主题”类型上不存在属性“排序” - TS2339: Property 'sort' does not exist on type 'BehaviorSubject<AbstractControl[] "Angular 获取 BehaviorSubject 值错误:“从不”类型上不存在属性“access_token”" - Angular getting BehaviorSubject value error: Property 'access_token' does not exist on type 'never' 如何从服务访问属性类型BehaviorSubject? - How can I take access to property type BehaviorSubject from service? 无法设置 BehaviorSubject 的订阅数据 - Unable to set subscribe data of BehaviorSubject 如何spyOn属性为BehaviorSubject / Observable的服务? - How to spyOn property of a Service that is a BehaviorSubject/Observable? BehaviorSubject 更改未反映在 UI 上的对象数组中的 1 个属性 - BehaviorSubject change 1 property in array of objects not reflecting on UI TypeError:无法读取未定义的 BehaviorSubject 的属性“next” - TypeError: Cannot read property 'next' of undefined BehaviorSubject Model 绑定属性与 BehaviorSubject(对于 ChangeDetectionStrategy) - Model Binding Property vs BehaviorSubject (For ChangeDetectionStrategy) 行为主体的访问元素 - Access Elements of BehaviorSubject
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM