简体   繁体   English

如何使用 Angular 4 及更高版本实现 JSON Schema Faker

[英]How to implement JSON Schema Faker with Angular 4 and above

Is it possible to use JSON Schema faker as a third party dependency in Angular.是否可以将 JSON Schema faker 用作 Angular 中的第三方依赖项。 I tried to use the dependency injection to Angular however in the providers I am not able to import jsonSchemaFaker.我尝试使用对 Angular 的依赖注入,但是在提供程序中我无法导入 jsonSchemaFaker。

angular.json angular.json

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

jsonSchemaFaker.service.ts jsonSchemaFaker.service.ts

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

app.module.ts app.module.ts

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

... ...

declare let jsf: any;

This is what I tried to Inject json schema faker as a dependency in my angular app.. I am getting .. Uncaught ReferenceError: jsf is not defined这就是我尝试将 json schema faker 作为依赖项注入到我的 angular 应用程序中的内容。我得到了 .. Uncaught ReferenceError: jsf is not defined

That is not how you use npm packages in an angular application.这不是您在 angular 应用程序中使用 npm 包的方式。

First off, navigate to the directory of your package.json in your application and install the package:首先,导航到应用程序中package.json的目录并安装包:

npm install json-schema-faker

Then, inside your components or your services, use it as such:然后,在你的组件或服务中,像这样使用它:

// 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'})

I had to change my providers and the declaration to我不得不将我的提供者和声明更改为

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

declare let JSONSchemaFaker: any;

Reason: the global name for JSON Schema Faker mentioned in that library is "JSONSchemaFaker".原因:该库中提到的 JSON Schema Faker 的全局名称是“JSONSchemaFaker”。 It was a mistake on my part to declare it as jsf.将其声明为 jsf 是我的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM