Angular7:拦截器未命中,无法找出问题

时间:2019-07-19 04:50:31

标签: node.js angular angular-ui-router

听起来有些琐碎,但是,我在后端具有逻辑,可以根据我对用户进行身份验证的方式来验证用户是否属于白名单用户。想法是如果用户不在列表中,则将其移动到403页。这是项目要求,此处不能使用内置的authguard等概念。

这是后端代码,可以正常工作。当用户不是auth时,它将直接发布到索引页面。

import * as express from 'express';

let router = express.Router();
router.use("/", (req, res, next) => {
let userName = userService.getUser(req);
if(req.originalUrl.indexOf('') !== -1 && userService.validateUser(userName) === false){
    console.log('[WARN] Not authorized access by user : '+ userName);
    return res.status(403).send("Authorization failure: Contact the EIS team to get access to this site.");
}}

现在我已经编写了一个应用程序拦截器服务:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import { HttpInterceptor, HttpRequest, HttpEvent, HttpHandler, HttpResponseBase } from '@angular/common/http';

@Injectable()
export class AppInterceptorService implements HttpInterceptor {
    // constructor(http: HttpClient) {
    //         console.log('construcot AppInterceptorService');
    // }
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log('********** coming*********');
      return next.handle(req).do(event => {
          console.log('********** coming');
        if (event instanceof HttpResponseBase) {
          const response = event as HttpResponseBase;
          if (response.status === 403) {
            window.location.href = 'https://my-403-page.com';
            return next.handle(req);
          }
        }
      });
    }
  }

我的app.module.ts包含拦截器

providers: [
{
  provide: HTTP_INTERCEPTORS,
  useClass: AppInterceptorService,
  multi: true
}
],

还在app.module.ts中导入了HTTPClientModule

import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http' 

可选信息->在app.component.ts中:

import { HttpClient } from '@angular/common/http';
export class AppComponent implements OnInit {
title = 'Upgrade Service Admin UI'

public user: User
public serviceVersion: ServiceVersion
private _userSub$: Subscription
private _serviceVersionSub$: Subscription

constructor(private _http: HttpClient, private _cdr: ChangeDetectorRef) {
}

ngOnInit() {
  console.log('appcomponent loading')
  this._serviceVersionSub$ = this._http.get('version')
.subscribe(data => {
  this.serviceVersion = data as ServiceVersion
  this._cdr.markForCheck()
})
this._userSub$ = this._http.get('user')
.subscribe(data => {
  this.user = data as User
  this._cdr.markForCheck()
})

我无法弄清楚是什么原因导致拦截器未被检测到。不熟悉Angular,感谢您对我的教育。

0 个答案:

没有答案