“对象”类型中不存在属性“位置”

问题描述 投票:0回答:2
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);
      });

    });

  }

enter image description here

我在这里很新,对离子很新,我可能需要详细的解决方案,我似乎无法让离子读取一个json文件

json windows typescript ionic-framework geolocation
2个回答
0
投票

enter image description here

您在data.locations中遇到编译时错误,特别是locations未在data属性上定义。

Fix

告诉TypeScript它是例如使用断言:

  this.data = this.applyHaversine((data as any).locations);

0
投票

如果您知道响应的类型,则可以向http.get<T>()添加泛型以键入data

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);
    ...
});
© www.soinside.com 2019 - 2024. All rights reserved.