Reputation: 151
I am a newbie in angular and am trying to get a list of properties referencing some previous examples I had already done. However I am given an error that type {} is not assignable to type IProperty[]
on the line
this.properties = properties;
. Any clarification to what might be going on
Below is the 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;
}
}
Property Interface
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)
}
}
Upvotes: 2
Views: 4400
Reputation: 691745
Your service says that it returns one IProperty
. The controller tries to assign that IProperty
to an array of IProperty
.
So, either the controller is right, and the service should use
this.http.get<Array<IProperty>>(...)
or the service is right, and the field should be declared as
property: IProperty = null;
I guess the former is what you actually want. You should aways declare what the service is supposed to return. The error would be much clearer:
getProperties(): Observable<Array<IProperty>> {
Upvotes: 5
Reputation:
First, your IProperty object might be a class and not an interface. You want to make an array of object so you cant do this :
this.properties = properties;
I think your API return a json object so you have to parse it before :
this.properties = JSON.parse(properties)
OR if your API return simple IProperty you have to push it to the array :
this.properties.push(properties);
Upvotes: 0
Reputation: 1076
Specify the type
properties:Array<IProperty> = [];
ngOnInit(){
this._apiService.getProperties().subscribe(properties:Array<IProperty> => {
this.properties = properties;
},
error => this.errorMessage = <any>error)
}
Upvotes: 3
Reputation: 41407
your observable returns an object instead of an array. you need to change properties
type as an object.
properties: IProperty = {};
Upvotes: 1