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

Cha*_*r08 2 typescript angular

我是角色的新手,我试图得到一个属性列表,引用我之前已经做过的一些例子.但是我收到一个错误,类型{}不能分配给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;
    }
}
Run Code Online (Sandbox Code Playgroud)

属性接口

export interface IProperty
{
    propertyId: number;
    propertyName: string;
    price: number;
    description: string;
}   
Run Code Online (Sandbox Code Playgroud)

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

JB *_*zet 5

您的服务表示它返回一个 IProperty.控制器试图分配一个IProperty到一个阵列IProperty.

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

this.http.get<Array<IProperty>>(...)
Run Code Online (Sandbox Code Playgroud)

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

property: IProperty = null;
Run Code Online (Sandbox Code Playgroud)

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

getProperties(): Observable<Array<IProperty>> {
Run Code Online (Sandbox Code Playgroud)