类型{}不能分配给类型[]

时间:2017-12-28 16:05:34

标签: angular typescript

我是角色的新手,我正在尝试获取一个属性列表,引用我之前已经完成的一些示例。但是我收到一条错误消息 类型{}无法分配到行中的IProperty[] 类型

  

this.properties = properties;

。对可能发生的事情的任何澄清

以下是component.ts

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

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

4 个答案:

答案 0 :(得分:5)

您的服务表示它返回一个 IProperty。控制器尝试将IProperty分配给IProperty数组

因此,控制器是正确的,服务应该使用

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

或服务是正确的,该字段应声明为

property: IProperty = null;

我猜前者是你真正想要的。你应该声明服务应该返回什么。错误会更清楚:

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

答案 1 :(得分:3)

指定类型

properties:Array<IProperty> = [];

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

答案 2 :(得分:1)

你的observable返回一个对象而不是一个数组。您需要将properties类型更改为对象。

properties: IProperty = {};

答案 3 :(得分:0)

首先,您的IProperty对象可能是一个类而不是一个接口。 你想创建一个对象数组,所以你不能这样做:

this.properties = properties;

我认为你的API会返回一个json对象,所以你必须先解析它:

this.properties = JSON.parse(properties)

如果你的API返回简单的IProperty,你必须将它推送到数组:

this.properties.push(properties);
相关问题