当我尝试调用class (getCoordinates())
的方法时,出现以下错误:
ERROR TypeError:this.locations [0] .getCoordinates不是函数
我的错误在哪里?
我的服务方式:
getLocations(){
return this.http.get<Location[]>(this.locationUrl);
}
我的模特:
export class Location {
id: number;
objectTypeId: number;
type: string;
fields: Fields;
fav: boolean;
typeless: boolean;
pages: number;
lastmodified: string;
public getCoordinates(): number {
return this.id;
}
}
export class Fields {
city: string;
street: string;
company: string;
plz: string;
info: string;
}
我的组件
public locations: Array<Location> = [];
ngOnInit() {
this.getAddresses();
}
getAddresses() {
this.enaioService.getLocations()
.subscribe(data =>
this.locations = data,
(error: HttpErrorResponse) => this.errorMessage = error.message
);
}
onClick() {
console.log(this.locations[0].getCoordinates()); // Here the error occurs
}
https://stackblitz.com/edit/angular-bjgtn4
我的项目:https://bitbucket.org/sven_hagemann/myproject/src/master/
克隆:git clone https://sven_hagemann@bitbucket.org/sven_hagemann/myproject.git
答案 0 :(得分:0)
尝试一下
getLocations(): Observable<Location[]>{
return this.http.get<Location[]>(this.locationUrl)
.pipe(map( (items: any[]) =>
items.map(i => Object.assign(new Location(), i)); ));
}
答案 1 :(得分:0)
这是因为从您的Location
方法检索到的getLocations
对象的列表不是Location
类的实例。您现在拥有的只是打字稿语法语法糖,它说getLocations
返回的内容应该具有Location
类的属性,但不必如此。>
您需要按如下所示修改代码,以返回Location
类的真实实例
import {map} from "rxjs/operators";
getLocations(): Observable<Location[]>
{
return this.http.get(this.locationUrl).pipe
(map( (items: any[]) => items.map(i => Object.assign(new Location(), i));
));
}