简体   繁体   中英

NPM module “only refers to a type, but is being used as a value here.” in Ionic 2 / Angular 2

I'm trying to import the npm module "ajv" into my Ionic 2 (Angular 2) project. ( https://epoberezkin.github.io/ajv/ )

I ran "npm install ajv --save", then made the following changes to my app.modules.js file:

import { Ajv } from 'ajv';

...
providers : [
    Ajv,
    ...
]

When I compile, however, I get the error:

'Ajv' only refers to a type, but is being used as a value here.
c:/Users/me/Documents/Ionic/MyApp/src/app/app.module.ts

Is there a better way to pull in this library?

The providers array in NgModule is for use with @Injectable components or similarly functional "providers" or "services" in other speak. This library does not appear to conform to that design.

It's likely that all you really want to do is use the import within your application component, rather than in AppModule . By import I mean the simple ES6 style import of "symbol" and then direct usage in code.

So for example in example.component.ts :

import { Component } from '@angular/core';
import { Ajv } from 'ajv';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
})
export class ExampleComponent {

  myMethod() {
     // Just use Ajv here
  }

}

No need to put this in the decorator arrays.

If an imported third party library is rather something you want to use in a "service like manner", then by all means wrap it as an @Injectable service, but the consumption will stay much the same as the the above example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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