我正在使用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