我正在尝试使用.netcore webapi和Angular 7进行登录。我认为在拦截器中存在问题,请帮我解决这个问题。
@Injectable()
export class AuthInterceptor implements HttpInterceptor{
constructor(private router:Router) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>{
if(localStorage.getItem('token')!=null){
const cloendReq = req.clone({
headers: req.headers.set('Authorization','Bearer ' +localStorage.getItem('token'))
});
return next.handle(cloendReq).pipe(
tap(
succ =>{ },
err =>{
if(err.status = 401){
localStorage.removeItem('token');
this.router.navigateByUrl('/user/login');
}
}
)
)
}
else next.handle(req.clone());
}
}
登录
onSubmit(form:NgForm){
this.service.login(form.value).subscribe(
(res: any)=>{
localStorage.setItem('token',res.token);
this.router.navigateByUrl('/home');
},
err =>{
if(err.status == 400)
this.toster.error('Incorrect UserName or Password','Authantication Failed!')
else
console.error(err)
}
);
}