angular 4 —— HttpClient拦截器无错,就是没反应?

大白two
  • 166
  1. angular是4.3.6的。
  2. 代码是参考网上的:

InterceptorService

// http 请求拦截器
import {Injectable, Pipe} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import {ErrorObservable} from 'rxjs/observable/ErrorObservable';
import {LocalStorageService} from './local-storage.service';
import {mergeMap} from 'rxjs/operator/mergeMap';

@Injectable()
export class InterceptorService implements HttpInterceptor {

  constructor(private storage: LocalStorageService) {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // 排除不需要进行token验证的接口
    const excludeUrl = ['login', 'unregistration'];  // 登入和登出不需要token验证
    let isNotVerifyToken = false;  // 排除状态
    excludeUrl.map(item => {
      if (request.url.indexOf(item) > -1) {
        isNotVerifyToken = true;
      }
    });

    if (!isNotVerifyToken) {
      // 此处获取localstorage的Token
      if (this.storage.getToken()) {
        const promise = this.storage.getToken();

        const authReq = request.clone({
          headers: request.headers.set('Authorization', 'token:' + promise)
        });

        return next.handle(authReq);

      }
    } else {
    }
  }
}

app.module.ts

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

@NgModule({
imports: [
    HttpModule,
    HttpClientModule,
  ],
providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: InterceptorService,
      multi: true
    }
]
})

没报错,就是不运行,不知道咋回事...

回复
阅读 1.3k
1 个回答

这个问题就这样关闭吧,反正我也没找到问题。因为我现在去使用vue了!哈哈哈哈

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
你知道吗?

宣传栏