typescript Angular HttpInterceptor

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了typescript Angular HttpInterceptor相关的知识,希望对你有一定的参考价值。

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { User } from '@models';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

    get Token(): string {
        const u: User = JSON.parse(localStorage.getItem('user'));
        let token: string;
        u === null ? token = '' : token = u.access_token;
        return token;
    }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        request = request.clone({
            setHeaders: {
                Authorization: `Bearer ${this.Token}`,
                Accept: 'application/json'
            }
        });
        return next.handle(request);

    }

}
      
// Register the TokenInterceptor in the same module where the HttpClientModule is imported

import { HttpClientModule, HTTP_INTERCEPTORS  } from '@angular/common/http';
import { TokenInterceptor } from './token.interceptor';

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

以上是关于typescript Angular HttpInterceptor的主要内容,如果未能解决你的问题,请参考以下文章

Angular 指令依赖注入 - TypeScript

typescript Angular 4基本动画#angular #js

Angular (TypeScript) 模型

如何将变量放入语句 [Angular,TypeScript]

Angular + TypeScript 是否为最佳实践?

Angular 2 Typescript 编译错误