html - 在实现 ngrx Observable 时显示未知类型的对象

标签 html angular typescript ngrx-store angular-ngrx-data

这是我组件的 typescript 代码:

import { Component, Input, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';

@Component({
    selector: 'app-counter-output',
    templateUrl: './counter-output.component.html',
    styleUrls: ['./counter-output.component.css']
})
export class CounterOutputComponent implements OnInit {
    counter!: number;
    counter$!: any;

    constructor(private store: Store<{ counter: { counter: number } }>) {
    }

    ngOnInit(): void {

        this.store.select('counter').subscribe((data) => {
            this.counter = data.counter;
            console.log(data);
        });
        this.counter$ = this.store.select('counter');
        console.log(this.counter$);
    }
}

这是它的 HTML 模板:

<div>This is the counter:{{(counter$|async).counter}}</div>
<div>This is the counter:{{counter}}</div>

HTML 文件中的第 1 行有错误。

enter image description here

当我订阅 typescript 文件时,我能够获取该值,但是当我将它用作可观察值时,它显示错误。

最佳答案

将类型设置为 counter$ .

export interface Counter {
    counter: number;
}

...

counter$: Observable<Counter>;

当然,你必须确保选择器返回 Counter作为数据。

编辑:如果您坚持使用 any (这超出了使用 Typescript 的目的),您可以使用 $any() type cast function抑制此错误。

<div>This is the counter:{{ ($any(counter$|async)).counter }}</div>

关于html - 在实现 ngrx Observable 时显示未知类型的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70155338/

相关文章:

javascript - HTML5 Canvas toDataURL 返回空白

html - 将第三方设计整合到网络或移动应用程序中

angular - 如何在 keycloak 中设置 CORS 配置以允许 ajax 请求?

javascript - typescript 标记联合未在 switch 语句中进行类型检查

javascript - 我可以将函数导入 typescript 类文件吗?

html - 在eclipse中创建html页面

html - <select> 中的 <option> "label"属性有什么意义?

Angular 2 : about duplicated declarations of Template Reference Variable in a template

node.js - Angular 4 组件不加载 MEAN 堆栈

Angular 2 基本身份验证不起作用