类型“对象"上不存在属性“".可观察订阅 [英] Property '' does not exist on type 'Object'. Observable subscribe

查看:17
本文介绍了类型“对象"上不存在属性“".可观察订阅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用 Angular2,但遇到了一个我无法真正理解的问题.

I have just started with Angular2 and I've got an issue I cannot really understand.

我创建了一些模拟数据:

I have some mock data created as such:

export const WORKFLOW_DATA: Object =
{
    "testDataArray" : [
        { key: "1",              name: "Don Meow",   source: "cat1.png" },
        { key: "2", parent: "1", name: "Roquefort",    source: "cat2.png" },
        { key: "3", parent: "1", name: "Toulouse",   source: "cat3.png" },
        { key: "4", parent: "3", name: "Peppo", source: "cat4.png" },
        { key: "5", parent: "3", name: "Alonzo",     source: "cat5.png" },
        { key: "6", parent: "2", name: "Berlioz", source: "cat6.png" }
    ]
};

然后在服务中导入并观察"

Which is then imported in a service and "observed"

import { Injectable } from '@angular/core';

import { WORKFLOW_DATA } from './../mock-data/workflow'
import {Observable} from "rxjs";

@Injectable()
export class ApiService {

  constructor() { }

  getWorkflowForEditor(): Observable<Object>
  {
      return Observable.of( WORKFLOW_DATA );
  }

}

然后我有一个组件,在构造函数中:

I then have a component which, in the constructor:

constructor( private apiService: ApiService)
    {
        this.apiService.getWorkflowForEditor().subscribe( WORKFLOW_DATA => {
            console.log( WORKFLOW_DATA);
            console.log( WORKFLOW_DATA.testDataArray );
        } );
    }

第一个 console.log 记录一个 Object 类型的 Object,其中包含 testDataArray 属性.

The first console.log logs an Object of type Object which contains the testDataArray property.

第二个console.log,导致编译时出错:

The second console.log, results in an error at compile time:

Property 'testDataArray' does not exist on type 'Object'.

同时仍按预期记录对象数组 [Object, Object, ..].

While still logging an array of objects [Object, Object, ..] as intended.

我真的不明白为什么,我确定我做错了什么,我希望得到解释.

I really do not understand why, I am sure I am doing something wrong, I would love an explanation.

感谢您的帮助!

推荐答案

当你告诉 typescript 时:

When you tell typescript:

WORKFLOW_DATA:对象

您是在告诉它 WORKFLOW_DATA 是一个没有属性的普通对象.当您稍后尝试访问 WORKFLOW_DATA.testDataArray 时,编译器认为您误用了该类型.

You are telling it that WORKFLOW_DATA is a plain object with no attributes. When you later try to access WORKFLOW_DATA.testDataArray the compiler thinks you misusing the type.

如果您想对 WORKFLOW_DATA 进行类型检查,您需要创建一个描述您的对象的接口.

If you want type checking on WORKFLOW_DATA you need to create an interface that describes your object.

这篇关于类型“对象"上不存在属性“".可观察订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆