James Fallon
James Fallon

Reputation: 164

Angular 6 : Sending authenticated request

i am trying to implement angular2-jwt sending implementation request in angular 6 but i am getting errors that seem this package isn't available for angular 6

My code :

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

export function authHttpServiceFactory(http: Http, options: RequestOptions) {
  return new AuthHttp(new AuthConfig({
    tokenName: 'token',
        tokenGetter: (() => sessionStorage.getItem('token')),
        globalHeaders: [{'Content-Type':'application/json'}],
    }), http, options);
}

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

Error:

ERROR in node_modules/angular2-jwt/angular2-jwt.d.ts(3,10): error TS2305: Module '"D:/.../.../.../node_modules/rxjs/Observable"' has no exported member 'Observable'.
node_modules/rxjs/Observable.d.ts(1,15): error TS2307: Cannot find module 'rxjs-compat/Observable'.

Upvotes: 0

Views: 211

Answers (1)

Tsvetan Ganev
Tsvetan Ganev

Reputation: 8856

The version of angular-jwt you are using doesn't support Angular 6 and RxJS 6.

You should remove this version and install the newer one:

npm install @auth0/angular-jwt

and use it as follows:

import { JwtModule } from '@auth0/angular-jwt';
import { HttpClientModule } from '@angular/common/http';

export function tokenGetter() {
  return localStorage.getItem('jwt');
}

@NgModule({
  imports: [
    // this is the specific part
    HttpClientModule,
    JwtModule.forRoot({
      config: { tokenGetter }
    }),
  ]
})
export class AuthModule {}

This will make every HTTP request made with HttpClient inside the AuthModule have credentials automatically sent with it.

You can use the utility funcitons provided by the library (checking for token validity, etc.) by injecting JwtHelperService inside your components/services:

import { JwtHelperService } from '@auth0/angular-jwt';

@Injectable
export class MyService {
  constructor(private jwtUtil: JwtHelperService) {}
}

You can read the documentation here.

Upvotes: 1

Related Questions