Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

angular - Property '' does not exist on type 'Object'. Observable subscribe

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 );
        } );
    }

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

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

Property 'testDataArray' does not exist on type '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.

Thank you for any help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Typescript expects WORKFLOW_DATA to be Object here:

.subscribe( WORKFLOW_DATA => {} )

because you told it so:

  getWorkflowForEditor(): Observable<Object>

But Object doesn't have testDataArray property... You should either tell TypeScript that data can have any properties:

  getWorkflowForEditor(): Observable<any>

or use

console.log( WORKFLOW_DATA["testDataArray"] );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...