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

问题描述 投票:2回答:4

我是角色的新手,我试图得到一个属性列表,引用我之前已经做过的一些例子。但是我收到一个错误,类型{}不能分配给行上的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)
    }
}
angular typescript
4个回答
5
投票

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

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

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

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

property: IProperty = null;

我想前者是你真正想要的。您应该始终声明服务应返回的内容。错误会更清楚:

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

3
投票

指定类型

properties:Array<IProperty> = [];

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

1
投票

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

properties: IProperty = {};

0
投票

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

this.properties = properties;

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

this.properties = JSON.parse(properties)

或者,如果您的API返回简单的IProperty,您必须将其推送到数组:

this.properties.push(properties);
© www.soinside.com 2019 - 2024. All rights reserved.