AngHttp 6中的AuthHttp(从Angular2迁移到Angular6)

时间:2018-10-26 06:00:43

标签: angular jwt angular6 auth0 angular2-jwt

我最近将我的应用程序从 Angular2 迁移到了 Angular6

我的构建由于Angular2-JWT而失败,因此我将其升级到 @ auth0 / angular-jwt

现在,由于不赞成使用AuthHTTP和AuthConfig,我在更新代码时遇到了麻烦。

我的security.module.ts有一个factory.ts。而且我必须将新的AuthHttp返回到我的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);
}

现在,我在返回AuthHttp时遇到错误。

我的Security.Module.ts如下。

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

我在Provide上也出错:AuthHttp。

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

这是如何使用HttpClient和HttpHeaders作为服务添加身份验证

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}`) };
}

access_token是Json Web令牌。

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

https://angular.io/guide/http