[英]How to fetch JSON file in Angular 2
由於我是 Angular 的新手,任何人都可以提供一個使用 angular 2 加載 JSON 文件數據的簡單解決方案嗎?
我的代碼如下
索引.html
<html> <head> <title>Angular 2 QuickStart</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="css/styles.css"> <!-- 1. Load libraries --> <!-- Polyfill(s) for older browsers --> <script src="node_modules/core-js/client/shim.min.js"></script> <script src="node_modules/zone.js/dist/zone.js"></script> <script src="node_modules/reflect-metadata/Reflect.js"></script> <script src="node_modules/systemjs/dist/system.src.js"></script> <!-- 2. Configure SystemJS --> <script src="systemjs.config.js"></script> <script> System.import('app').catch(function(err){ console.error(err); }); </script> </head> <!-- 3. Display the application --> <body> <my-app>Loading...</my-app> </body> </html>
app.component.ts
import {Component} from '@angular/core'; @Component({ selector: 'my-app', template: ` <div id="main"> Main Div <div id = "header"></div> <div id = "content"> <ul class="games"> <li> </li> </ul> </div> </div> ` }) export class AppComponent { }
游戲.json
{ "games":[ { "title":"Primary Operations", "enabled":true }, { "title":"Curated Games", "enabled":false } ] }
我想把games.json中的所有游戲都取到app.component.ts的li里,請詳細指教。
這是我解析 JSON 的代碼的一部分,它可能對您有所幫助:
import { Component, Input } from '@angular/core';
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class AppServices{
constructor(private http: Http) {
var obj;
this.getJSON().subscribe(data => obj=data, error => console.log(error));
}
public getJSON(): Observable<any> {
return this.http.get("./file.json")
.map((res:any) => res.json())
.catch((error:any) => console.log(error));
}
}
將 json 文件保存在 Assets(與應用程序目錄平行)目錄中
請注意,如果您使用 ng new YourAppname 生成 - 此資產目錄與“app”目錄存在同一行,並且服務應該是應用程序目錄的子目錄。 可能如下所示:
::應用程序/服務/myservice.ts
getOrderSummary(): Observable {
// get users from api
return this.http.get('assets/ordersummary.json')//, options)
.map((response: Response) => {
console.log("mock data" + response.json());
return response.json();
}
)
.catch(this.handleError);
}
如果您使用 angular-cli 將 json 文件保存在 Assets 文件夾(與應用程序目錄平行)目錄中
return this.http.get('<json file path inside assets folder>.json'))
.map((response: Response) => {
console.log("mock data" + response.json());
return response.json();
}
)
.catch(this.handleError);
}
注意:這里你只需要在assets/json/oldjson.json之類的assets文件夾中提供路徑然后你需要像/json/oldjson.json這樣寫路徑
如果您使用 webpack,那么您需要在公共文件夾中遵循上述相同的結構,其類似於資產文件夾。
在 Angular 5
你可以說
this.http.get<Example>('assets/example.json')
這會給你Observable<Example>
你不需要HttpClient ,你甚至不需要 Angular。 你所需要的只是 WebPack 和 JSON-Loader,兩者都已經是 Angular-CLI 的一部分。
您需要的所有代碼就是這一行:
import * as someName from './somePath/someFile.json;
您的 json-data 可以在someName.default
下someName.default
。 然而,這段代碼會從 TypeScript 編譯器中拋出一個類型錯誤——這不是一個真正的錯誤,而只是一個類型錯誤。
要解決它,將此代碼添加到您的src/typings.d.ts
文件(如果它不存在,請創建它):
declare module "*.json"
{
const value: any;
export default value;
}
請注意:使用此方法將在構建時將您的 json (minify/uglify) 編譯到應用程序包中。 這意味着您無需等到此文件加載-就像您選擇使用httpClient.get(...)
-意味着更快的應用程序!
您需要對您的games.json
進行HTTP調用以檢索它。 就像是:
this.http.get(./app/resources/games.json).map
我認為資產文件夾是公開的,您可以直接在瀏覽器上訪問它
與其他 privates 文件夾不同,將您的 json 文件放在 assets 文件夾中
我需要同步加載設置文件,這是我的解決方案:
export function InitConfig(config: AppConfig) { return () => config.load(); }
import { Injectable } from '@angular/core';
@Injectable()
export class AppConfig {
Settings: ISettings;
constructor() { }
load() {
return new Promise((resolve) => {
this.Settings = this.httpGet('assets/clientsettings.json');
resolve(true);
});
}
httpGet(theUrl): ISettings {
const xmlHttp = new XMLHttpRequest();
xmlHttp.open( 'GET', theUrl, false ); // false for synchronous request
xmlHttp.send( null );
return JSON.parse(xmlHttp.responseText);
}
}
然后將其作為 app_initializer 提供,它在應用程序的其余部分之前加載。
app.module.ts
{
provide: APP_INITIALIZER,
useFactory: InitConfig,
deps: [AppConfig],
multi: true
},
service.service.ts
--------------------------------------------------------------
import { Injectable } from '@angular/core';
import { Http,Response} from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
@Injectable({
providedIn: 'root'
})
export class ServiceService {
private url="some URL";
constructor(private http:Http) { }
//getData() is a method to fetch the data from web api or json file
getData(){
getData(){
return this.http.get(this.url)
.map((response:Response)=>response.json())
}
}
}
display.component.ts
--------------------------------------------
//在這個組件中使用 suscribe() 獲取數據並將其作為 dataObject 存儲在本地對象中,並將數據顯示在 display.component.html 中,如 {{dataObject .propertyName}}。
import { Component, OnInit } from '@angular/core';
import { ServiceService } from 'src/app/service.service';
@Component({
selector: 'app-display',
templateUrl: './display.component.html',
styleUrls: ['./display.component.css']
})
export class DisplayComponent implements OnInit {
dataObject :any={};
constructor(private service:ServiceService) { }
ngOnInit() {
this.service.getData()
.subscribe(resData=>this.dataObject =resData)
}
}
例如,在您聲明@Component之前的組件中
const en = require('../assets/en.json');
public init() { return from( fetch("assets/server-config.json").then(response => { return response.json(); }) ) .pipe( map(config => { return config; }) ) .toPromise(); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.