3
votes

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.

1
Imho, the AuthHttp was quite useless service. I was using it long time ago and switched to using Angular's HttpClient where I set headers myself (which is pretty much all you need to do). One less dependency and clearer code.Enn
Appreciate your answer. But I cannot figure out how to use HttpClient instead of AuthHttp. Can you please show me how to do it?Joseph Vinodh
HttpClient is Angular's built-in module/service for executing HTTP requests. Its quite likely that some version of AuthHttp is using that as well. Try looking here angular.io/guide/http If you need to add authentication headers globally, you might as well create your own service, use HttpClient in it, add headers and use this in your app. You would basically create your own 'AuthHttp'.Enn
Import "Http, RequestOptions and Headers from @angular/http and add request options to response. Header Authorization should contain token. let headers = new Headers(); let token = localStorage.getItem('token'); headers.append('Authorization', 'Bearer ' + token) let options = new RequestOptions({ headers: headers });Maludasek

1 Answers

2
votes

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