我在从嵌套JSON读取数据并加载到ngx_table时遇到问题。 我的JSON看起来像:
[
{
"Patientage": 29,
"Patientname": "Moran",
"Drugs": [
{
"DrugName": "Dolo",
"Dosage": "150 mg daily",
"MedicationDuration": "3 years",
"MedicationType": "Current"
},
{
"DrugName": "Paracetamol",
"Dosage": "200 mg daily",
"MedicationDuration": "2.5 years",
"MedicationType": "Current"
}
],
"Reactions": [
{
"Start Date": "10-10-2017",
"End Date": "15-10-2017"
}
]
}
我的AppComponent.ts
:
export class AppComponent implements OnInit {
constructor (private httpService: HttpClient) { }
arrCase : object [];
Drugs : object [];
Drug : string[] ;
ngOnInit () {
this.httpService.get('./assets/Case.json').subscribe(
data => {
this.arrCase = data as object []; // FILL THE ARRAY WITH DATA.
console.log(this.arrCase);
this.Drugs = data["Drugs"] ;
console.log(this.Drugs)
this.Drug = this.Drugs["DrugName"];
console.log(Drug);
},
(err: HttpErrorResponse) => {
console.log (err.message);
}
);
}
}
无法从药物清单中获取药物清单或个别药物(反应信息不会打印到控制台)。
我的控制台(1)msg:
30/05/2018: 我正在将药物组织到数据服务/稍后在MatTable上使用相同的CRUD。
export class DataService {
private readonly API_URL = './assets/Case.json';
dataChange: BehaviorSubject<Drug[]> = new BehaviorSubject<Drug[]>([]);
// Temporarily stores data from dialogs
dialogData: any;
Drugs : object [];
constructor (private httpClient: HttpClient) {}
get data(): Drug[] {
return this.dataChange.value;
}
getDialogData() {
return this.dialogData;
}
/** CRUD METHODS */
getAllDrugs(): void {
this.httpClient.get<Drug[]>(this.API_URL).subscribe(data => {
let res = data[0];
this.Drugs = res['Drugs'];
// this.dataChange.next(data)
this.dataChange.next(this.Drugs)
console.log(this.Drugs)
},
(error: HttpErrorResponse) => {
console.log (error.name + ' ' + error.message);
});
}
请注意,this.dataChange.next(数据)是将药物加载到表格所必需的,它可以使用简单的json(当我的json只有药物,没有反应或患者信息时)。 当我嵌套JSON时,我们可以在 this.Drug 中获得编码的药物。随后如何 使用&#34; this.Drugs&#34;使用datachange.next? - 请指导我。 谢谢 阿沙
答案 0 :(得分:1)
export class AppComponent implements OnInit {
arrCase: object [];
Drugs: object [];
Drug: string[];
constructor(private httpService: HttpClient) {}
ngOnInit() {
this.httpService.get('./assets/Case.json').subscribe(
data => {
this.Drugs = this.getDrugs(data);
},
(err: HttpErrorResponse) => {
console.log(err.message);
});
}
getDrugs(data):any {
return data.map((item)=>item.Drug));
}
}
通过getDrugs方法你可以获得药物清单;