我正在尝试使用 Ajv (我正在使用 typescript )。
import { Ajv } from "ajv";
let ajv = new Ajv({allErrors: true});
只是想知道为什么会出现这个错误:
[ts] 'Ajv' only refers to a type, but is being used as a value here.
我像文档一样使用它:
var Ajv = require('ajv');
var ajv = new Ajv(); // options can be passed, e.g. {allErrors: true}
var validate = ajv.compile(schema);
var valid = validate(data);
if (!valid) console.log(validate.errors);
但是我使用 import 而不是 require 所以我没有设置变量,所以我猜这是导致错误的原因。当使用 import
而不是 require
时,我该如何定义使用变量?
所有代码:
import { Injectable } from "@angular/core";
import { Http, Headers, Response } from "@angular/http";
import { Configuration } from "../shared/configuration.model";
import { Observable } from "rxjs/Rx";
import { Ajv } from "ajv";
@Injectable()
export class ValidateJSONSchemaService {
constructor(private http: Http) { }
public valJson(json, schemaFile: string) {
return new Promise((resolve, reject) => {
this.http.get(schemaFile)
.toPromise()
.then(fileContents => fileContents.json())
.then((schema) => {
let ajv = new Ajv({allErrors: true});
ajv.validate(schema, json) ?
resolve() :
reject(new Error("JSON does not conform to schema: " + ajv.errorsText()));
}, err => reject(
new Error("Unable to get schema file contents:" + err))
);
});
};
}
最佳答案
正如@elclanrs 所说,使用import * as Ajv from 'ajv'
不是想占功劳,但已经一年了,我几乎错过了答案,因为没有任何标记为答案。
关于typescript - 用导致错误的 Import 语句替换 Require 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41795341/