使用Angular throws错误从内部json文件解析json数据

时间:2019-07-05 11:23:30

标签: json angular components

我试图从angular内的内部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中。

谢谢

1 个答案:

答案 0 :(得分:0)

getVillages是服务中的一种方法,因此您需要在使用它之前实例化该服务。

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

app.module.ts

...
providers : [
    RecordsService
]
...

在您的组件中,

abc.component.ts

constructor(public recordService : RecordsService) {
}

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

让我知道您是否仍然遇到错误或有其他错误。

EDIT

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

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