【问题标题】:problem in using angular2-jwt and AuthHttp when upgrading angular from 4 to 6将 Angular 从 4 升级到 6 时使用 angular2-jwt 和 AuthHttp 的问题
【发布时间】:2019-05-26 22:28:04
【问题描述】:

我正在尝试将 angular4 应用程序更新为 angular6,并且我正在使用 angular2-jwt 向 web api 发送身份验证,但是在 angular6 中我发现了这个错误: TypeError: Observable_1.Observable.defer is not a function see the error here

这是我创建令牌的地方

 login(model: any) {
    const headers = new Headers({ 'Content-type': 'application/json' });
    const options = new RequestOptions({ headers: headers });
    return this.http
      .post(this.baseUrl, model, options)
      .map((response: Response) => {
        const user = response.json();
        if (user) {
          localStorage.setItem('token', user.userModel.tokenString);
          this.decodedToken = this.jwtHelper.decodeToken(user.userModel.tokenString);
          this.userToken = user.userModel.tokenString;
          this.currentUserModel = user.userModel;
          this.changeuserPhotoUrl(this.currentUserModel.userImage);
        }
      }).catch(this.handelError);
  }

这是我的 HttpServiceFactory

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

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

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

export class AuthenticationModule { }

【问题讨论】:

    标签: angular authentication angular6 asp.net-core-webapi angular2-jwt


    【解决方案1】:

    我认为您可以使用 Interceptor 来实现您的目的。例如;

    @Injectable()
    export class AuthInterceptor implements HttpInterceptor {
     .......
     .....
    }
    

    然后你应该把它放到你的module.ts中

    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthInterceptor,
      multi: true
    }
    

    【讨论】:

      猜你喜欢
      • 2019-03-30
      • 1970-01-01
      • 2017-04-01
      • 2020-03-21
      • 2019-02-21
      • 1970-01-01
      • 2019-10-04
      • 2017-10-31
      • 1970-01-01
      相关资源
      最近更新 更多