角度发送令牌与获取(和其他)请求 [英] Angular sending token with get (and other) requests

查看:70
本文介绍了角度发送令牌与获取(和其他)请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某种原因,Internet上缺少有关如何在Angular 4中执行此操作的示例(该示例使用TypeScript,该脚本不允许您跳过选项属性,例如它转换为JavaScript的属性).

For some reason, the internet is devoid of examples on how to do this in Angular 4 (which uses TypeScript, which doesn't let you skip including option properties like the JavaScript it transpiles into does).

我正在尝试使用团队的RESTful API,该API需要带有GET请求的身份验证令牌,例如:

I'm trying to hit my team's RESTful API, which requires an authentication token, with GET request, like, for example :

return this.http.get(this.BASE_URL + '/api/posts/unseen/all', {
            headers : {
                "Authorization": 'Token token="' + TokenService.getToken() + '"'
            }   
        })

其中TokenService是我编写的用于返回令牌以在应用程序中使用的业务服务类.键入后,我反而收到此错误:

where TokenService is business service class I wrote to return token for use in the app. Upon typing it up, I get greeted with this error instead:

我在其中显示的服务文件中的依存关系是:

My dependencies in the service file this appears in are:

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';

import { Post } from '../models/post'; // business class 
import 'rxjs/';
import { User } from '../models/user'; // business class
import { HttpService } from './http.service'; // service for connecting us to the base location of the endpoints. provides BASE_URL to any service that extends it
import { TokenService } from './token.service'; // token provider

注意:我尝试复制并粘贴该错误,但是Visual Studio Code不会配合我这样做.

NOTE: I tried copying and pasting that error, but Visual Studio Code would not cooperate with me doing that.

推荐答案

使用新的httpClient可以更轻松地发送令牌.首先,您必须定义一个拦截器

Using the new httpClient makes it easier to send token. First you will have to define an interceptor

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

@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);
  }
}

您必须将拦截器添加到您的提供程序中:

You have to add the interceptor to your provider:

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

@NgModule({
  bootstrap: [AppComponent],
  imports: [...],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: TokenInterceptor,
      multi: true
    }
  ]
})
export class AppModule {}

现在,当您发出任何请求时,令牌将自动出现在标题中.

Now when you make any request, the token will be present automatically in the headers.

import { HttpClient } from '@angular/common/http';
// ...
export class AppComponent {

  constructor(public http: HttpClient) {}

  public connectServer() {
    this.http.get('url')
      .subscribe(
        data => console.log(data),
        err => console.log(err)
      );
  }

}

在拦截器中,我使用服务来检查令牌是否有效.这不是强制性的,因为您可以定义自己的authenticationService.但是您可以使用以下一种方法:

In the interceptor I use a service to check if the token is valid. It is not compulsory as you can define your own authenticationService. But here is one you can use:

import { Injectable } from '@angular/core';
import decode from 'jwt-decode';

@Injectable()
export class AuthService {

  public getToken(): string {
    return localStorage.getItem('token');
  }

  public isAuthenticated(): boolean {
    // get the token
    const token = this.getToken();
    // return a boolean indicating whether or not the token is expired
    return tokenNotExpired(token);
  }

}

这篇关于角度发送令牌与获取(和其他)请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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