【问题标题】:Property 'locations' does not exist on type 'Object'“对象”类型上不存在属性“位置”
【发布时间】:2019-02-11 04:23:55
【问题描述】:
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

我在这里很新,对 ionic 也很陌生,我可能需要详细的解决方案,我似乎无法让 ionic 读取 json 文件

【问题讨论】:

    标签: json windows typescript ionic-framework geolocation


    【解决方案1】:

    如果您知道响应的类型,则可以将泛型添加到 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);
        ...
    });
    

    【讨论】:

      【解决方案2】:

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

      修复

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-11
        • 2018-02-10
        • 2018-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-23
        • 2020-09-27
        相关资源
        最近更新 更多