我正在使用angular-cli工具使用Typescript編寫Angular 2應用程序。 我有一堆JSON模式用於我的後端API,我想在我的打字稿中引用,因此我可以將這些模式傳遞給模式驗證程序。包含.json文件的最好方法是什麼,這樣我可以在打字稿中將它們作爲變量引用,並且在使用angular-cli進行構建時也可以將它們正確地捆綁在一起?在typescript中包含json模式文件
我的第一個想法是製作一個自定義模塊並將每個模式導出爲一個常量。我不確定這是否可能,並且無法找到任何關於如何引用這些文件的示例語法。
這是我現在可用的示例代碼。唯一的問題是我不得不將模式文件內容複製到我的typesrcipt中。我希望能夠引用原始模式文件。
import { Injectable } from "@angular/core";
import { Http, Response } from "@angular/http";
import { Observable } from "rxjs/Observable";
import { WlanStatus } from "./wlan-status";
import { JsonValidatorService } from "../../json-validator.service";
//import WlanStatusSchema from "../../../api/app/plugins/wifi/schemas/getStatus.json";
const wlanStatusSchema =
{
"type": "object",
"properties": {
"result": {
"type": "object",
"properties": {
"cardState": {
"type": "integer"
},
"profileName": {
"type": "string"
},
"clientMAC": {
"type": "string"
},
"clientIP": {
"type": "string",
"format": "ipv4"
},
"clientName": {
"type": "string"
},
"AP_MAC": {
"type": "string"
},
"AP_IP": {
"type": "string"
},
"APName": {
"type": "string"
},
"Channel": {
"type": "integer"
},
"RSSI": {
"type": "integer"
},
"bitRate": {
"type": "integer"
},
"txPower": {
"type": "integer"
},
"DTIM": {
"type": "integer"
},
"beaconPeriod": {
"type": "integer"
},
"SSID": {
"type": "string"
},
"currentRadioMode": {
"type": "integer"
}
},
"required": [
"cardState",
"profileName",
"clientMAC",
"clientIP",
"clientName",
"AP_MAC",
"AP_IP",
"APName",
"Channel",
"RSSI",
"bitRate",
"txPower",
"DTIM",
"beaconPeriod",
"SSID",
"currentRadioMode"
]
}
},
"required": [
"result"
]
};
@Injectable()
export class WlanService
{
private getStatusUrl = 'app/getWlanStatus'; // URL to web API
constructor(private http: Http, private validator: JsonValidatorService) { }
scan(): void
{
console.log("Scanning for APs...")
}
getStatus(): Observable<WlanStatus>
{
return this.issueRequest(this.getStatusUrl, wlanStatusSchema);
}
private issueRequest(requestUrl: string, schema: any): Observable<Object>
{
return this.http.get(requestUrl)
.map((res: Response) =>
{
let body = res.json();
let valid = this.validator.validate(schema, body.data);
if (!valid)
{
throw (new TypeError("Not a valid response: " + JSON.stringify(this.validator.getErrors())));
}
return body.data.result;
})
.catch(this.handleError);
}
private handleError(error: Response | any)
{
// In a real world app, we might use a remote logging infrastructure
let errMsg: string;
if (error instanceof Response)
{
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else
{
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}
謝謝你的建議,將工作,但不是我的方案。問題是我希望能夠直接在我的前端代碼中引用.json文件的內容。 – Ryan