无法识别的可观察的儿童节点
我有以下数据对象接口:(
interface MainGameObject {
credits: Credit[];
localisation: Localisation;
}
我当然也声明了信用和本地化的类型)。
在我的组件中,我将我的gamedata $
对象声明为可观察的,因为我希望将其与模板中的异步管一起使用。
gameData$ = of({}) as Observable<MainGameObject>;
ngOnInit() {
this.gameData$ = this.generalService.getAllGameData();
}
到目前为止,这效果很好。但是,如果我想在文件中其他位置的“信用”或“本地化”的子节点(例如:
getCredits()
{
console.log(this.gameData$.credits);
}
我的VS代码)说以下错误:
Property 'credits' does not exist on type 'Observable<MainGameObject>'
为什么?已专门声明了MaingameObject导入我的根对象,“信用”或“本地化”。
我可以在模板方面列出内容,即:*ngfor =“让(gamedata $ | ynnc)?打字稿文件。
I have the following data object interface:
interface MainGameObject {
credits: Credit[];
localisation: Localisation;
}
(Am I of course declaring the types for credits and localisation too).
In my component I declare my gameData$
object as an observable as I wish to use this with the async pipe in my template.
gameData$ = of({}) as Observable<MainGameObject>;
ngOnInit() {
this.gameData$ = this.generalService.getAllGameData();
}
And so far this works fine. However if I wish to get the child nodes of either 'credits' or 'localisation' elsewhere in my file such as:
getCredits()
{
console.log(this.gameData$.credits);
}
My VS code says the following error:
Property 'credits' does not exist on type 'Observable<MainGameObject>'
Why? MainGameObject imports my root object and 'credits' or 'localisation' have been specifically declared.
I can list out things on the template side ie: *ngFor="let credit of (gameData$ | async)?.credits"
but I can't access it in the typescript file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
gamedata $
是可观察的
,它没有credits
属性,正如错误消息所说的那样。您使用async
管道中的模板中使用此可观察的
,它允许您订阅它,并访问它发出的值,但仅在模板中。如果您也想在组件类文件中使用它,则需要向其手动订阅
。您可以将另一个属性添加到类中,并为其分配这样的值:
但是,此方法的缺点是您必须手动取消订阅此
可观察的
。模板中的async
管道不是这种情况,该管道自动订阅,然后在销毁组件时最终取消订阅。不这样做会在您的应用程序中创建内存泄漏。gameData$
is anObservable
, which does not havecredits
property, as the error message says so. You are using thisObservable
in the template with theasync
pipe, which allows you to subscribe to it, and access the values it emits, but only in the template. If you want to use it in your component class file as well, you will need to manuallysubscribe
to it.You can add another property to the class, and assign it the value like this:
However, the drawback of this approach is that you have to manually unsubscribe to this
Observable
. This is not the case with theasync
pipe in the template, which automatically subscribes and then eventually unsubscribes when the component is destroyed. Not doing so will create a memory leak in your application.