首页 > 解决方案 > 使用 Angular 解析内部 json 文件中的 json 数据抛出错误

问题描述

我试图从角度内的 tne 内部 json 文件中获取 json。

使用此服务(village.service):

import { Injectable, OnInit } from '@angular/core';
import { Http, Response } from '@angular/http';
import { environment } from '../../environments/environment';
import { Observable } from 'rxjs'
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

@Injectable()
export class RecordsService {

data: any;

  constructor(private http: Http) { }

  getVillages(id) {
 return this.http.get('../assets/data/villages.json')
    .map(data => {
       this.data = data.json();
       return data.json();
    }, err => {
    if (err) {
      return err.json();
    }
  });
  }

}

在commponet下我放了:

ngOnInit() {

this.getVillages();

....
}

并在此处加载为链下拉列表

  onSubDistrictSelected(subDistrictId: number) {
    if (subDistrictId) {
      this.onLoading.emit(true);
      this.customer.subDistrict = this.subDistricts.filter(c => (c.id == subDistrictId))[0].name;
      this.customer.sdid = subDistrictId;
      this.customer.subDistrictId = subDistrictId;
      this.villages = this.getVillages().filter((item) => {
      return item.subDistrictId === Number(subDistrictId)
      });
      this.onLoading.emit(false);
    }
  }

编译时出现错误提示:this.getVillages不起作用,但是如果我将 json 值放入组件文件中,则可以正常工作:

getVillages() {
    return [
      { json_data}
      ]
    }

我想要实现的是我想使用 JSon 文件而不是直接放在 commponet 中。

谢谢,

标签: jsonangularcomponents

解决方案


getVillages是服务中的方法,所以在使用前需要实例化服务。

首先,您需要RecordsService在模块中提供,例如,

app.module.ts

...
providers : [
    RecordsService
]
...

在你的组件中,

abc.component.ts

constructor(public recordService : RecordsService) {
}

ngOnInit() {
   this.recordService.getVillages();
}

如果您仍然收到错误或有其他错误,请告诉我。

编辑

getVillages()正在返回一个 Observable,因此您需要订阅才能使用返回的数据。

this.recordService.getVillages().subscribe( data => {
    console.log(data);
} )

推荐阅读