将angular从4升级到6时使用angular2-jwt和AuthHttp的问题

时间:2018-12-29 12:46:14

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

我正在尝试将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 { }

1 个答案:

答案 0 :(得分:0)

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

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

然后应该将其放入模块中。

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