2017-12-28 11 views
2

私は初心者です。私がすでに行ったいくつかの前例を参照するプロパティのリストを取得しようとしています。しかし、私は、タイプ{}は、ライン上のIProperty[]タイプ{}はタイプ[]に割り当てられません

this.propertiesの=プロパティを入力する割り当て可能ではないというエラーを与えています。

。以下は

に行くかもしれないものへの任意の明確化が

import {HttpClient, HttpErrorResponse} from '@angular/common/http'; 
import {Injectable} from '@angular/core'; 

import {Observable} from 'rxjs/Observable'; 
import 'rxjs/add/observable/throw'; 
import 'rxjs/add/operator/catch'; 
import 'rxjs/add/operator/do'; 

import {IProperty} from '../properties/property'; 

@Injectable() 
export class ApiService{ 
    handleError: any; 
    properties= []; 
    constructor (private http: HttpClient){} 

    getProperties(){ 
     return this.http.get<IProperty>('http://localhost:4200/properties').do(data => console.log('All: '+ JSON.stringify(data))) 
     .catch(this.handleError) 
    } 
} 
+0

私はあなたのAPI(バックエンド)は、オブジェクトを返します。..、あなたは、配列 –

+1

ポストapiServiceに割り当てしようとしていると思います。おそらく間違っています。 –

+0

@federicoscamuzziこれはコンパイルエラーであり、実行時エラーではありません。したがって、バックエンドが返すものとは何の関係もありません。 –

答えて

4

あなたのサービスは、それが返すことを言う IProperty。コントローラは、IPropertyアレイに割り当て、IPropertyに割り当てようとします。

ので、コントローラのどちらかが正しい、およびサービスは

this.http.get<Array<IProperty>>(...) 

を使うべきか、サービスが権利である、と私は前者が何をされると思い

property: IProperty = null; 

としてフィールドを宣言する必要がありますあなたは実際に欲しい。あなたは、サービスが返すと思われるものを先に宣言する必要があります。エラーがより明確になります:

getProperties(): Observable<Array<IProperty>> { 
1

あなたの観察可能なリターンオブジェクトの代わりに、

import {Component, OnInit} from '@angular/core'; 
import {IProperty} from './property'; 
import {ApiService} from '../api/api.service'; 

@Component({ 
    selector:'property', 
    templateUrl: '.property.component.html' 
}) 

export class PropertyComponent implements OnInit{ 
    errorMessage: any; 
    properties:IProperty[] = []; 

    constructor(private _apiService: ApiService){} 

    ngOnInit(){ 
     this._apiService.getProperties() 
     .subscribe(properties => { 
      this.properties = properties; 
     }, 
     error => this.errorMessage = <any>error) 
    } 

    private newFunction() { 
     return this.properties; 
    } 
} 

プロパティインタフェース

export interface IProperty 
{ 
    propertyId: number; 
    propertyName: string; 
    price: number; 
    description: string; 
} 

apiService component.tsですアレイ。あなたはオブジェクトとしてpropertiesタイプを変更する必要があります。

properties: IProperty = {}; 
+0

それは受け入れられる答えでなければなりません。 –

3

タイプ

properties:Array<IProperty> = []; 

ngOnInit(){ 
    this._apiService.getProperties().subscribe(properties:Array<IProperty> => { 
     this.properties = properties; 
    }, 
    error => this.errorMessage = <any>error) 
} 
0

まずを指定し、あなたのIPropertyオブジェクトはクラスではなくインターフェイスであるかもしれません。 あなたはこれを行う傾けるようにオブジェクトの配列を作りたい:

this.properties = properties; 

私はあなたが前にそれを解析する必要がありますので、あなたのAPIは、JSONオブジェクトを返すと思う:

this.properties = JSON.parse(properties) 

たり、APIの戻りの場合シンプルIPropertyあなたは配列にプッシュする必要があります。

this.properties.push(properties); 
関連する問題