简体   繁体   中英

Angular Interceptor executes before the request is finished

I have a HTTP request which retrieves a token:

login(email:any,password:any){

      this.http.post<{token:string}>('http://localhost:3000/login',{payload:{email,password}},{
      headers:new HttpHeaders({'Content-Type':'application/json'})
    }).pipe().subscribe(res=>{this.token=res.token
    console.log(this.token)})
}

And an interceptor:

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

    const authToken = this.authService.getToken();
    console.log('token'+authToken)
    const authReq=req.clone({
        headers: req.headers.set('Authorization',"Bearer " + authToken)
    })
    return next.handle(authReq);
}

The interceptor use getToken() whic is part of the same service as login():

getToken() {

  console.log(this.token)
  return this.token;
}

The problem is that the interceptor executes before the request is finished so after the first request token in getToken() is undefined , after the second request it returns the value of the first request etc. How can I prevent running the interceptor before retrieving data is over?

I have tried to place a condition in the interceptor but it didn`t worked.

you need to exclude this url, from intercept by the Interceptor , because this URL is in charge of getting the token

  intercept(req: HttpRequest<any>, next: HttpHandler) {
    if (!req.url.startsWith("/login") {

    const authToken = this.authService.getToken();
    console.log('token'+authToken)
    const authReq=req.clone({
        headers: req.headers.set('Authorization',"Bearer " + authToken)
    })
    return next.handle(authReq);
    }
    else return next;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM