2017-08-17 6 views
1

私は角度4を学習しており、クラスメソッドを取得する方法を理解できません。サービスによって実装されたときに、角度クラスメソッドが機能しない

私はこの機能のクラスを持っています。これには、Google Charts JSONデータテーブルを構築するためのいくつかのメソッドが含まれています。

export class Feature { 
    id: string; 
    name: string; 

    get cols() { 
     return [ 
     {'id': '', 'label': 'id', 'type': 'string'}, 
     {'id': '', 'label': 'name', 'type': 'string'} 
     ]; 
    } 

    get row() { 
     console.log('foo'); 
     return {'c': [ {'v': this.id}, {'v': this.name} ] }; 
    } 

} 

私はRESTのAPIから機能を移入するサービスがあります。

import { Injectable } from '@angular/core'; 
import { Headers, Http } from '@angular/http'; 

import 'rxjs/add/operator/toPromise'; 
import { Feature } from './feature'; 

@Injectable() 
export class FeatureService { 
    private featureUrl = 'http://raspi/rest/api'; 

    constructor(private http: Http) { } 

    getFeatures(): Promise<Feature[]> { 
    return this.http.get(this.featureUrl + '/getFeatures') 
     .toPromise() 
     .then(response => response.json().results as Feature[]) 
     .catch(this.handleError); 
    } 

    private handleError(error: any): Promise<any> { 
    console.error('An error occurred', error); // for demo purposes only 
    return Promise.reject(error.message || error); 
    } 
} 

はその後、私のコンポーネントでは、INITに、私はサービスを呼び出し、とGoogleにインスタンスの配列を変換しようデータテーブル:

import { Component, OnInit } from '@angular/core'; 
import { Feature } from '../feature'; 
import { FeatureService } from '../feature.service'; 

@Component({ 
    selector: 'app-features', 
    templateUrl: './features.component.html', 
    styleUrls: ['./features.component.css'] 
}) 
export class FeaturesComponent implements OnInit { 
    features: Feature[]; 

    public tableData = { 
    chartType: 'Table', 
    dataTable: {}, 
    options: {'title': 'Tasks'}, 
    }; 

    constructor(
    private featureService: FeatureService 
) { } 

    private features2dataTable(features: Feature[]) { 
    const data = { 
     'cols': [], 
     'rows': [] 
    } 

    features.forEach(function(feature) { 
     console.log(feature); 
     data.cols = feature.cols; 
     data.rows.push(feature.row); 
    }); 
    console.log(data); 
    return data; 
    } 

    getFeatures(): void { 
    this.featureService 
     .getFeatures() 
     .then(features => this.tableData.dataTable = this.features2dataTable(features)) 
    } 

    ngOnInit(): void { 
    this.getFeatures(); 
    } 

} 

私はDataTableのは、この形式を持つようにしたい:

{ 
    "cols": [ 
     {"id":"","label":"Topping","pattern":"","type":"string"}, 
     {"id":"","label":"Slices","pattern":"","type":"number"} 
     ], 
    "rows": [ 
     {"c":[{"v":"Mushrooms","f":null},{"v":3,"f":null}]}, 
     {"c":[{"v":"Onions","f":null},{"v":1,"f":null}]}, 
     {"c":[{"v":"Olives","f":null},{"v":1,"f":null}]}, 
     {"c":[{"v":"Zucchini","f":null},{"v":1,"f":null}]}, 
     {"c":[{"v":"Pepperoni","f":null},{"v":2,"f":null}]} 
     ] 
} 

が、私はfeature.rowまたはfeature.colsを使用するとき、私は「ID」と、インスタンスの「名前」フィールドが移入されていても、バック未定義の取得:

{id: "BP01", name: "BP feature one"} 
    id: "BP01" 
    name: "BP feature one" 
    __proto__: Object 
    features.component.ts:30 

{id: "BP02", name: "BP feature two"} 
    id: "BP02" 
    name: "BP feature two" 
    __proto__: Object 
    features.component.ts:34 

{cols: undefined, rows: Array(2)} 
    cols: undefined 
    rows: (2) [undefined, undefined] 
    __proto__: Object 

なぜ得ることはありません方法の仕事?

+0

なぜあなたは同じ行にこれをやっているが、 'this.tableData.dataTable = this.features2dataTable(機能)それを分離'。 –

+0

あなたが受け取っているレスポンスが期待しているクラス定義に合っていない可能性がありますか? console.log(response.json())の結果はどうですか? –

+0

「id」フィールドと「name」フィールドに正しく入力されています。これは、私のfeatures.forEachループ内でconsole.log(機能)を実行すると表示されました。問題は、各フィーチャには「id」フィールドと「name」フィールドしかなく、クラスで定義されている「行」または「cols」メソッドがないことです。 AJT_82問題を識別しました。私はFeatureオブジェクトの代わりにPOJOをループしていました。 –

答えて

2

すること...

.then(response => response.json().results as Feature[]) 

は実際にはFeatureというオブジェクトの配列を作成しないため、POJOだけなので、クラス固有のメソッドにアクセスすることはできません。

あなたが明示的にあなたのクラスのオブジェクトのインスタンスを作成する必要があるので、このような何か:

getFeatures() { 
    return this.http.get(this.featureUrl + '/getFeatures') 
    .toPromise() 
    .then(response => response.json().results.map(obj => Object.assign(new Feature(), obj))) 
    .catch(this.handleError); 
} 
+0

ありがとう!これは私の問題を解決しました。これは私にとって非常に直観的ではないようです。 angular.io/tutorialに続いて、Heroオブジェクトを格納するためのHeroクラスを作成することが暗示されているようです。クラスをインポートし、クラスが無視されPOJOが返された場合に "as Feature []"でそれを使用する目的は何ですか? –

+0

徹底的に起こっていることは、**タイプアサーション**です。私たちは、データの見た目がわかっていることをコンパイラに伝えます。ここで読むことができます:https://basarat.gitbooks.io/typescript/content/docs/types/type-assertion.html :) – Alex

0

私の最初の考えはあなたがセッターとゲッターの両方を定義する必要があるということです。

export class Feature { 
    id: string; 
    name: string; 
    private _cols; 

    get cols() { 
     return this._cols; 
    } 

    set cols() { 
     this._cols = [ 
     {'id': '', 'label': 'id', 'type': 'string'}, 
     {'id': '', 'label': 'name', 'type': 'string'} 
     ]; 
    } 

    /** 
     Same as above for rows 
    */ 

} 

あなたがここに型としてクラスを使用しているので、これは、正しくない可能性があります - あなたのコンソールに.log @ line 30、行全体ではなく、colデータだけを取得していますか?正しいデータが得られていないようです。

あなたはこのような何かしたい:

[ 
    { 
    cols: [...], 
    row: {...} 
    } 
] 

をしかし、あなたが取得している:

[ 
{...} // col & row data 
] 

features2datatable関数に渡された機能にはconsole.logをやってみて、これは操縦必要がありますがあなたは正しい方向にあなた:

関連する問題