【问题标题】:typescript error on assignment of subscribe event订阅事件分配上的打字稿错误
【发布时间】:2019-02-21 17:50:06
【问题描述】:

这是我的 ts 代码:在 this.store.pipe 之后,我将数据分配给 courseList - 但出现打字错误:

错误 src/app/setup-config/setup-config/setup-config.component.ts(55,4): 错误 TS2740:类型“ModelCourse[]”缺少以下属性 来自“可观察”类型:_isScalar、源、运算符、 提升,还有 5 个

这是什么意思?我需要在这里做什么更正?

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

import { Store, select } from '@ngrx/store';
import { StateSetupConfig, ModelCourse } from "./../models";
import { LoadCourse } from "./../state/course.actions";
import * as setupConfigActions from "./../state/setup-config.actions";
import * as actions from "./../state";

import { Observable } from 'rxjs';
declare var $:JQueryStatic;

@Component({
    selector: 'setup-config',
    templateUrl: './setup-config.component.html',
    styleUrls: ['./setup-config.component.scss']
})
export class SetupConfigComponent implements OnInit {


    courseList:Observable<ModelCourse[]>


    constructor(private store:Store<StateSetupConfig>) { }

    ngOnInit(){ 


        this.store.dispatch(new LoadCourse());

        this.store.pipe(select(actions.getCourses)).subscribe((data:ModelCourse[]) => {
            this.courseList = data;
        })

    }


}

【问题讨论】:

    标签: angular typescript angular7


    【解决方案1】:

    问题是您试图将ModelCourse[] 类型的实际值分配给Observable&lt;ModelCourse[] 类型的类成员。

    最简洁的方法是直接分配您的商店选择器,例如:

    public readonly courseList$ = this.store.pipe(
      select(actions.getCourses),
    );
    

    在您的模板中使用async-pipe 来检索如下值:

    <div *ngFor="let course of courseList$ | async">
      <!-- example -->
    </div>
    

    这样您就不必在组件销毁时取消订阅。

    一点网站注释: 如果您在多个地方使用数据并且总是想要最新的值,您可以在 select 运算符之后将 shareReplay 运算符添加到您的流中。

    【讨论】:

    • 但是我这里需要订阅,因为我需要使用map给数组对象添加一个额外的属性...
    • 无需订阅,只需使用rxjs操作符(例如map操作符)应用修改即可。
    • 所以这是正确的:public readonly courseList$ = this.store.pipe( select(actions.getCourses).map(data =&gt; ...),); - 得到错误map dosen't existing on Observable&lt;ModelCourse[]&gt;
    • 不,您必须使用 rxjs 运算符,例如:store.pipe(select(...), map(...))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    • 2020-12-06
    • 2022-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多