【问题标题】:How to use the map operator in rxjs within an angular 7 app?如何在 Angular 7 应用程序中使用 rxjs 中的地图运算符?
【发布时间】:2019-07-07 22:08:54
【问题描述】:

我的代码已编译,一切正常,但我的 IDE(Visual Studio 代码)显示以下错误消息,我无法部署我的应用程序(使用 ng build --prod):

src/app/training/training.service.ts(61,46) 中的错误:错误 TS2339: 类型“{}”上不存在属性“名称”。 src/app/training/training.service.ts(62,50):错误 TS2339:属性 类型“{}”上不存在“持续时间”。 src/app/training/training.service.ts(63,50):错误 TS2339:属性 “{}”类型不存在“卡路里”。

我像这样导入地图运算符:

import { map, take } from 'rxjs/operators';

并像这样使用它:

...
    .snapshotChanges()
    .pipe(
      map(docArray => {
        return docArray.map(doc => {
          return {
            id: doc.payload.doc.id,
            name: doc.payload.doc.data().name,
            duration: doc.payload.doc.data().duration,
            calories: doc.payload.doc.data().calories
          };
        });
      })
    )
...

我的界面是这样的:

export interface Exercise {
id: string;
name: string;
duration: number;
calories: number;
date?: Date;
state?: 'completed' | 'cancelled' | null;

}

我做错了什么?

【问题讨论】:

  • 使用此代码的方法返回什么type
  • 它是对 firebase 数据库/集合的订阅,并从那里获取数据。我将使用过的界面添加到我的问题中。我感觉这是由于第二个嵌套的地图功能。因为不是rxjs操作符,而是普通的Javascript方法..

标签: angular rxjs ngrx angular7 rxjs6


【解决方案1】:

为了愚弄 Typescript,你可以这样做:

doc => {

    let result: any = doc.payload.doc.data();
          return {
            id: doc.payload.doc.id,
            name: result.name,
            duration: result.duration,
            calories: result.calories
          };

【讨论】:

  • 这就是它的工作原理,但是为什么我的版本会出现错误消息?导入是正确的,我也使用管道语法。这真的只与我的 IDE 有关吗?
  • 我认为这与您的导入、语法或 IDE 无关。 data() 函数可能有错误的签名,或者没有在 Typescript 中定义的签名。那么打字稿将不允许您使用 data().id。将其重新定义为任何让 typescript 在此处跳过类型检查。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-28
相关资源
最近更新 更多