首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >类型'Object‘上不存在属性'locations’

类型'Object‘上不存在属性'locations’
EN

Stack Overflow用户
提问于 2018-09-06 08:47:34
回答 2查看 900关注 0票数 0
代码语言:javascript
运行
复制
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文件

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-09-06 08:50:23

data.locations中会出现编译时错误,特别是在data属性上没有定义locations

修复

告诉TypeScript它是这样的,例如使用断言:

代码语言:javascript
运行
复制
  this.data = this.applyHaversine((data as any).locations);
票数 0
EN

Stack Overflow用户

发布于 2018-09-06 10:27:30

如果您知道响应的类型,则可以将泛型添加到类型datahttp.get<T>()中。

代码语言:javascript
运行
复制
interface SomeInterface {
    locations: Location[]
}

this.http.get('assets/data/locations.json')<SomeInterface>.subscribe(data => {
    this.data = this.applyHaversine(data.locations);
    ...
});

或者如果你不想为它创建一个接口(不推荐)

代码语言:javascript
运行
复制
this.http.get('assets/data/locations.json')<SomeInterface>.subscribe((data: any) => {
    this.data = this.applyHaversine(data.locations);
    ...
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52195025

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档