json - 使用 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 中。
谢谢,
解决方案
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);
} )
推荐阅读
- docker - 由于 ssh 密钥,Git 推送失败:主机密钥验证失败。从码头工人内部
- javascript - 从 React 组件调用函数时的异步行为
- reactjs - 从道具中的函数反应返回字符串
- java - Apache POI 3.17 HSSF 不接受“IFERROR”
- reactjs - React lazy load won't work inside React perfect scroll bar
- c++ - Doubly Linked List with struct c++
- spring - Spring Boot 数据源配置
- javascript - Using jQuery to auto calculate amount
- python - How to reset a global variable and pass it to Decorator
- mysql - What is wrong with the following trigger before an update?