如何使用 Angular 4 及以上版本实现 JSON Schema Faker

How to implement JSON Schema Faker with Angular 4 and above

是否可以在 Angular 中使用 JSON Schema faker 作为第三方依赖项。我尝试使用 Angular 的依赖注入,但是在提供者中我无法导入 jsonSchemaFaker.

angular.json

"scripts": [
    "./node_modules/json-schema-faker/dist/json-schema-faker.bundle.min.js"
]

jsonSchemaFaker.service.ts

import { InjectionToken } from '@angular/core';
export const JSF_Token = new InjectionToken ('jsonSchemaFaker');

app.module.ts

providers: [
    { provide: JSF_Token, useValue: jsf }
]

...

declare let jsf: any;

这就是我试图在我的 angular 应用程序中注入 json schema faker 作为依赖项的方法。我得到了 .. Uncaught ReferenceError: jsf is not defined

这不是您在 angular 应用程序中使用 npm 包的方式。

首先,导航到应用程序中 package.json 的目录并安装包:

npm install json-schema-faker

然后,在您的组件或服务中,这样使用它:

// at the top of your file, next to other imports
import jsf from 'json-schema-faker';

// json-schema-faker is now available in the rest of your file as jsf

// you can, for example, have a service method that returns that:
jsf.generate({type: 'string'})

我不得不将我的提供商和声明更改为

providers: [
    { provide: JSF_Token, useValue: JSONSchemaFaker }
]

declare let JSONSchemaFaker: any;

原因:该库中提到的 JSON Schema Faker 的全局名称是 "JSONSchemaFaker"。我将其声明为 jsf 是错误的。