0
Iは、関数内のコードのブロックを有する:非同期関数
this.apiService.fetchCategories(!this.cacheData).subscribe(
response => {
if(this._jsnValService.valCategories(response)) {
this.customerMap.categories = this.formatCategories(response["categories"]);
} else {
alert("Categories failed the schema validation. Please contact support if this happens again.");
}
},
error => {
this.notification.title = "Oops, there's a problem.";
this.notification.content = "Seems there's an issue getting the provider categories.";
this.notification.show("provider_categories_api");
}
);
それはいくつかのデータをフェッチした後、データ(if(this._jsnValService.valCategories(response)) {
)の検証を実行します。
しかし、データの検証は実際には非同期でもあります。なぜなら、ファイルを最初に読み取る必要があるように、別のjsonファイルにあるjsonスキーマに対して検証するからです。 if(this._jsnValService.valCategories(response)) {
(私はif文の内部で非同期機能を説明するために、この問題の一番上のコードブロックを編集することができますどのように
@Injectable()
export class ValidateJSONSchemaService {
constructor(private http: Http) {}
public valCategories(json) {
this._getSchema("./jsonSchema.categories.json").then((schema) => {
this._valSchema(json, schema);
});
};
private _valSchema(json, schema): any {
var ajv = new Ajv();
var valid = ajv.validate(schema, json);
if (!valid) {
console.log(ajv.errors);
return false;
} else {
console.log(valid);
return true;
};
};
private _getSchema(fileName): any {
return new Promise((resolve, reject) => {
this.http.get(fileName)
.map(this._extractData)
.catch(this._handleError)
.subscribe(schema => resolve(schema));
});
};
private _extractData(res: Response) {
let body = res.json();
return body.data || {};
};
:
私は、ファイルの内容を読み取るために約束を使用して、検証を行ういます)?あなたは非同期を使用することができES6を使用している場合
最初に、あなたはPromiseを返すか、コールバック引数を受け入れるために 'valCategories'が必要です。つまり、その関数を使用するためにトップブロックを変更する機会はありません。 2番目のブロック?それはjavascriptではない –
@JaromandaX私はtypescriptを使用しています。誤解を招くes6-promiseタグをおかしかった。私は明日の仕事でこの質問に戻り、下の答えの一番下のコードブロックを試してみます。乾杯 – BeniaminoBaggins