Angular 4.3 Interceptor无法正常工作 [英] Angular 4.3 Interceptor not working

查看:95
本文介绍了Angular 4.3 Interceptor无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用新的 Angular 4.3 拦截器为所有请求设置authorithation标头。但是,它不起作用。我将断点设置为拦截器拦截方法并且浏览器没有点击它,所以看起来像 angular 只是忽略了我的拦截器。请帮助我,提前谢谢。

I try to use new Angular 4.3 interceptors for setting authorithation header for all requests. However, it is not working. I set breakpoint into the interceptors intercept method and browser did not hit it, so it seems like angular just ignores my interceptor. Please help me, thanks in advance.

user.service.ts:

user.service.ts:

import {Injectable} from '@angular/core';
import 'rxjs/add/operator/map';
import {Observable} from "rxjs";
import {Http} from "@angular/http";

@Injectable()
export class UserService {

  constructor(public http: Http) {
  }

  public getContacts(): Observable<any[]> {
    return this.http.get('/users/contacts').map(contacts => contacts.json());
  }
}

token.interceptor.ts

token.interceptor.ts

import {Injectable} from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import {AuthService} from "./shared/auth.service";

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor(public auth: AuthService) {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    request = request.clone({
      setHeaders: {
        Authorization: `Bearer ${this.auth.getToken()}`
      }
    });
    return next.handle(request);
  }
}

app.module.ts:

app.module.ts:

@NgModule({
  ...
  providers: [
    ...
    {provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true}
  ]
})


推荐答案

原因 - 您使用旧的 Http 服务而不是新服务,在 Angular 4.3中引入 - HttpClient Http 将被弃用)。此外,在 HttpClient 默认情况下假定JSON响应类型,因此您应该省略 .map(contacts => contacts.json())

The reason - you use old Http service instead of new service, introduced in Angular 4.3 - HttpClient (Http is going to be deprecated). Also, in the HttpClient JSON response type is assumed by default, so you should ommit .map(contacts => contacts.json()).

app.module.ts

app.module.ts

...
import { HttpClientModule } from '@angular/common/http';

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

user.service.ts

user.service.ts

...
import {HttpClient} from "@angular/common/http";

@Injectable()
export class UserService {

  constructor(public http: HttpClient) {
  }

  public getContacts(): Observable<any[]> {
    return this.http.get('/users/contacts');
  }
}

这篇关于Angular 4.3 Interceptor无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆