我无法在Angular5中的拦截器服务中分配更新的令牌

时间:2018-04-21 20:10:11

标签: angular typescript rxjs interceptor angular-http-interceptors

我的拦截器中出现了一个打字稿错误

  

找不到名称'authReq'。

如何转换我的代码以便我的拦截器正确捕获寄存器组件设置的访问令牌并且typescript显示没有错误?

User.Service.ts - >在这里,我将access_token声明为BehavioralSubject

  access_token = new BehaviorSubject<string>('');

Register.component.ts - &gt;在这里我成功地将值分配给access_token

 onRegister(form){
    this.httpService.registerByEmail(this.email, this.password )
    .subscribe(
      response => {
        this.httpService.loginByEmail(this.email, this.password)
        .subscribe(response1 => {
          this.userService.access_token.next(response1['access_token']);
        })
    })
  }

Auth.Interceptor.ts

import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
// services
import { UserService } from '../../services/data/user/user.service';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  constructor(private userService: UserService) { }
  authToken;

  intercept(req: HttpRequest<any>, next: HttpHandler) {

    this.userService.access_token.subscribe(
      token => {
      this.authToken = token;
        const authReq = req.clone({
          headers: req.headers.set('Authorization', `Bearer ${this.authToken}`)
        });
        return authReq;
      }
    )
    return next.handle(authReq);  
  }
}

2 个答案:

答案 0 :(得分:1)

问题是,authReq订阅之外没有access_token。你也在这样做:return next.handle(authReq);这个陈述本身就是同步的,所以这不会等你的订阅完成。

我不知道它是否符合您的需求,但我认为您应该做的是: 而不是订阅,为map执行access_token并返回地图下的next。然后susbscribeintercept下的任何一个函数调用它。

return this.userService.access_token.map(
  token => {
  this.authToken = token;
    const authReq = req.clone({
      headers: req.headers.set('Authorization', `Bearer ${this.authToken}`)
    });
    return next.handle(authReq);
  }
)

答案 1 :(得分:0)

试试这个

intercept(req: HttpRequest<any>, next: HttpHandler) {

return this.userService.access_token.flatMap(
  token => {
    this.authToken = token;
    const authReq = req.clone({
        headers: req.headers.set('Authorization', `Bearer ${this.authToken}`)
       });
       return next.handle(authReq);  
   }
)}