Joseph Vinodh
Joseph Vinodh

Reputation: 31

AuthHttp in Angular 6 (Migration from Angular2 to Angular6)

I've recently migrated my application from Angular2 to Angular6

My build failed because of Angular2-JWT so I upgraded it to @auth0/angular-jwt

Now I'm stuck while updating my code as AuthHTTP and AuthConfig are deprecated.

I have a factory.ts for my security.module.ts. And I have to return a New AuthHttp to my security.module.ts.

export function AuthHttpServiceFactory( http: Http, options: RequestOptions) {
  const accessToken = this.accessTokenService.getAccessToken();
  const userInfoToken = this.accessTokenService.getUserInfoToken();
  return new AuthHttp(
    new AuthConfig({
      tokenName: 'token',
      tokenGetter: (() => accessToken),
      globalHeaders: [{ 'Content-Type': 'application/json' }, { 'userinfotoken': userInfoToken }],
    }), http, options);
}

Now I'm getting error while returning AuthHttp.

My Security.Module.ts is as follows.

@NgModule({
  providers: [
    LocalStorageService,
    {
      provide: AuthHttp,
      useFactory: AuthHttpServiceFactory,
      deps: [Http, RequestOptions]
    }
  ]
})

I'm getting error at Provide : AuthHttp also.

Any help is appreciated.

Upvotes: 3

Views: 2301

Answers (1)

Chigozie Madubuko
Chigozie Madubuko

Reputation: 69

this is how to add authentication using HttpClient and HttpHeaders as a service

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';


@Injectable({
providedIn: 'root'
})
export class VehicleService {

headers;
private readonly vehicleEndpoint = 'api/vehicles';


constructor(private http: HttpClient) {

}


create(vehicle) {
    return this.http.post(this.vehicleEndpoint, vehicle, this.addHeaders());
}

addHeaders() {
    var access_token = localStorage.getItem('access_token');
    return { headers: new HttpHeaders().set("Authorization", `Bearer   
${access_token}`) };
}

the access_token is the Json Web Token.

https://angular.io/api/common/http/HttpHeaders

https://angular.io/guide/http

Upvotes: 2

Related Questions