[英]Can't show data from local json file in browser
I want to show JSON data in browser so that model, provider, storage and condition displays in separate divs. 我想在浏览器中显示JSON数据,以便模型,提供程序,存储和条件显示在单独的div中。 There is no error in console and i can't figure out where is the problem. 控制台中没有错误,我不知道问题出在哪里。 Link updated for stackblitz, kindly have a look into it. 链接更新为stackblitz,请查看一下。
Here is the link for stackblitz. 这是stackblitz的链接。
iphone.json iphone.json
{
"model": [
"iPhone 5",
"iPhone 5s",
"iPhone SE"
],
"provider": [
"Unlocked",
"AT&T"
],
"storage": [
"16",
"32"
],
"condition": [
"Brand New",
"Mint"
]
}
sell.service.ts sell.service.ts
import { Injectable } from '@angular/core';
import { Observable } from "rxjs/Observable";
import { Http, Response } from "@angular/http";
import { HttpClient} from '@angular/common/http';
import "rxjs/add/operator/map";
export interface Staticdata {
model: Array<Model>;
provider: Array<Provider>;
storage: Array<Storage>;
condition: Array<Condition>;
}
export interface Model {
name: string;
}
export interface Provider {
carrier: string;
}
export interface Storage {
size: number;
}
export interface Condition {
quality: string;
}
@Injectable()
export class SellService {
fileUrl = '../static-data/iphone.json';
constructor(public http:HttpClient) {}
getData(){
return this.http.get(this.fileUrl);
}
}
sell-iphone.component.ts 卖方iphone.component.ts
import { Component, OnInit } from '@angular/core';
import { SellService, Staticdata } from "../shared/sell.service";
import * as data from "../static-data/iphone.json";
@Component({
selector: 'app-sell-iphone',
templateUrl: './sell-iphone.component.html',
styleUrls: ['./sell-iphone.component.css'],
providers: [ SellService ]
})
export class SellIphoneComponent implements OnInit {
constructor(public sellService: SellService){
}
ngOnInit() {}
staticData : Staticdata;
showData(){
return this.sellService.getData().subscribe((data: Staticdata) => this.staticData = {
model: data.model,
provider: data.provider,
storage: data.storage,
condition: data.condition
});
}
}
your json must be like: 您的json必须像:
{
"model": [
{
"name": "iPhone 5"
},
{
"name": "iPhone 5s"
},
{
"name": "iPhone SE"
}
],
"provider": [
{
"carrier": "Unlocked"
},
{
"carrier": "AT&T"
}
],
"storage": [
{
"size": "16"
},
{
"size": "32"
}
],
"condition": [
{
"quality": "Brand New"
},
{
"quality": "Mint"
}
]
}
Or you must transform the data you received. 否则您必须转换收到的数据。 You can do it in the service better than in the component. 您可以在服务中比在组件中更好地做到这一点。
getData(){
return this.http.get(this.fileUrl).pipe(map((res:any)=>{
return {
model:res.model.map(m=>{return {name:m}}),
provider:res.provider.map(p=>{return{carrier:p}}),
storage:res.storage.map(s=>{return{size:s}}),
condition:res.condition.map(c=>{return{quality:c}})
}
})
);
}
If you're using angular-cli, you must put your file.json in the folder "assets" 如果您使用的是angular-cli,则必须将file.json放在文件夹“ assets”中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.