尝试显示来自 Firebase observable 的对象属性时出现错误“TS2571:对象类型为‘未知’”

时间:2021-06-14 17:51:01

标签: angular firebase rxjs

我正在学习至少 7 个 Angular 旧版本的教程。我预计必须解决不推荐使用的代码,但我找不到有关如何做同样事情的最新示例。我只是想显示 Observable 中包含的 json 对象的属性。

这是app.component.ts的代码:

import { Component, OnInit } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/database';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
    author$;

    constructor(private db: AngularFireDatabase) {
        this.author$ = db.object('/authors/1').valueChanges();
        
    }

}

在标记中,

<p>
    {{ (author$ | async).name }}
</p>

会在标题中产生错误。但是,如果我改为写:

<p>
    {{ author$ | async | json }}
</p>

网页将完整显示对象:

<块引用>

{ "isPremium": true, "name": "Name Name", "students": 100 }

那么如何使用插值来呈现特定内容?我可能还应该说本教程是关于使用“as”关键字将这段代码缩写成这样的:

<ul *ngIf="author$ | async as author">
    <li>{{ author.name }}</li>
    <li>{{ author.isPremium }}</li>
    <li>{{ author.students }}</li>
</ul>

2 个答案:

答案 0 :(得分:1)

通过更改我声明 author$ 属性的方式,我能够使其正常工作。以前我声明它没有类型。现在它在声明后正常工作:

export class AppComponent {
    author$: Observable<any>;
...

带有标记:

<ul *ngIf="author$ | async as author">
    <li>{{ author.name }}</li>
    <li>{{ author.isPremium }}</li>
    <li>{{ author.students }}</li>
</ul>

我还应该注意,如果正确声明了属性,@ck706 提供的语法也有效

答案 1 :(得分:0)

很确定这应该适用于未知类型。我假设 Firebase 返回一个匿名对象。如果它返回一个 JSON 字符串,则可能需要在等式中加入 JSON.parse()。

<ul *ngIf="author$ | async as author">
    <li>{{ author['name']}}</li>
    <li>{{ author['isPremium'] }}</li>
    <li>{{ author['students'] }}</li>
</ul>