Search code examples
angularauthenticationjwtangular2-jwt

No provider for AuthHttp! on angular2-jwt


im really new on Angular 2 and i want to use JWT on my project. So i follow the instructions exactly where a give from the official page of angular2-jwt using the basic configuration. I create a file named auth.module.ts with the following code:

import { NgModule } from '@angular/core';
import { Http, RequestOptions } from '@angular/http';
import { AuthHttp, AuthConfig } from 'angular2-jwt';

function authHttpServiceFactory(http: Http, options: RequestOptions) {
  return new AuthHttp(new AuthConfig(), http, options);
}

@NgModule({
  providers: [
    {
      provide: AuthHttp,
      useFactory: authHttpServiceFactory,
      deps: [Http, RequestOptions]
    }
  ]
})
export class AuthModule {}

The next step are sending a Authenticated Request. I use a component where i put a button that invokes a function that execute the code suggested on the page:

File: calendario.components.ts

import {Component, OnInit,trigger,state,style,transition,animate,keyframes, group} from '@angular/core';
import initDemo = require('../../../assets/js/charts.js');
import initNotify = require('../../../assets/js/notify.js');
import { AuthHttp } from 'angular2-jwt';

declare var $:any;

@Component({
    moduleId: module.id,
    selector: 'calendario',
    templateUrl: 'calendario.component.html'

})

export class CalendarioComponent{
    thing: any;
    constructor(public authHttp: AuthHttp) {}
    obtenerDatos() {
        this.authHttp.get('http://localhost/autorepuestos/web/app_dev.php/api/conjunto')
      .subscribe(
        data => this.thing = data,
        err => console.log(err),
        () => console.log('Request Complete')
      );
        console.log("Hola");
    }
}

When i enter on this component i have a error:

EXCEPTION: Uncaught (in promise): Error: No provider for AuthHttp!
Error: DI Error

Any idea that i can resolve this? I really new on angular 2, thanks for your help!


Solution

  • Looks like you've created a module that will provide this AuthHttp class. Have you made sure that the AuthModule is in the imports of the module that CalendarioComponent is a part of?

    Something like this:

    import { AuthModule } from '...';
    import { CalendarioComponent } from '...';
    
    @NgModule({
        imports: [AuthModule],
        declarations: [CalendarioComponent]
    })
    export class SomeModule {}