import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
@Injectable()
export class LocationsProvider {
data: any;
constructor(public http: HttpClient) {
}
load() {
if (this.data) {
return Promise.resolve(this.data);
}
return new Promise(resolve => {
this.http.get('assets/data/locations.json').subscribe(data => {
this.data = this.applyHaversine(data.locations);
this.data.sort((locationA, locationB) => {
return locationA.distance - locationB.distance;
});
resolve(this.data);
});
});
}
我是这里的新手,也是ionic的新手,我可能需要详细的解决方案,我似乎不能让ionic读取json文件
发布于 2018-09-06 08:50:23
在data.locations
中会出现编译时错误,特别是在data属性上没有定义locations
。
修复
告诉TypeScript它是这样的,例如使用断言:
this.data = this.applyHaversine((data as any).locations);
发布于 2018-09-06 10:27:30
如果您知道响应的类型,则可以将泛型添加到类型data
的http.get<T>()
中。
interface SomeInterface {
locations: Location[]
}
this.http.get('assets/data/locations.json')<SomeInterface>.subscribe(data => {
this.data = this.applyHaversine(data.locations);
...
});
或者如果你不想为它创建一个接口(不推荐)
this.http.get('assets/data/locations.json')<SomeInterface>.subscribe((data: any) => {
this.data = this.applyHaversine(data.locations);
...
});
https://stackoverflow.com/questions/52195025
复制相似问题