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

问题描述

我刚开始使用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.

谢谢您的帮助!

推荐答案

告诉打字稿时:

WORKFLOW_DATA: Object

您正在告诉它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.

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

09-05 11:49