本文介绍了Angular 2+中的Web令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过登录组件将POST请求发送到后端REST API.我在响应标头中获得了x-auth令牌.如何获取和存储此令牌,以便在用户登录会话期间将其用于所有其他API请求?干杯

I am sending a POST request to a back end REST API, via a login component. I get an x-auth token back in the response headers.How do I get and store this token so I can use it for all other API requests for the duration of the users logged in session?Cheers

推荐答案

localStorage.setItem('token', response.access_token);

这就是我使用Angular 5的方法:

This is how I did it with Angular 5:

我的LoginService:

My LoginService:

import { Injectable } from '@angular/core';
import { HttpHeaders, HttpParams } from '@angular/common/http';

import { HttpService } from '../services/http.service';

@Injectable()
export class LoginService{
    constructor(private _http: HttpService) {
    }

    login(user: string, pass: string) {
        const params = new HttpParams()
            .append('grant_type', 'password')
            .append('username', user)
            .append('password', pass);
        const headers = new HttpHeaders()
            .set('Content-Type', 'application/x-www-form-urlencoded');
        return this._http.post('login', params, { headers: headers });
    }
}

我的登录组件:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

import { LoginService } from '../../services';

@Component({
    selector: 'app-login',
    templateUrl: './login.component.html'
})
export class LoginComponent implements OnInit {
    public pageTitle = 'User login';
    errorMessage = '';
    loginFormGroup: FormGroup;
    constructor(
        private fb: FormBuilder,
        private _loginService: LoginService) { }
    ngOnInit() {
        this.formBuild();
    }

    formBuild() {
        this.loginFormGroup = this.fb.group({
            loginUser: ['', [Validators.required]],
            loginPass: ['', [Validators.required]],
        });
    }

    onLogin() {
        let response: any;
        this._loginService.login(this.loginFormGroup.value.loginUser, this.loginFormGroup.value.loginPass)
            .subscribe(
                response => { response= response; },
                error => { this.errorMessage = <any>error; },
                () => {

                    localStorage.setItem('token', response.access_token);
                });
    }
}

我将令牌保存在localeStorage中.

I keep my token in localeStorage.

我已经创建了用于此令牌的拦截器:

I have created interceptors for usage of this token:

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

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const token = localStorage.getItem('token');
        request = request.clone({
            setHeaders: {
                Authorization: `Bearer ${token}`
            }
        });
        return next.handle(request);
    }
}

export const TokenInterceptorProvider = {
    provide: HTTP_INTERCEPTORS,
    useClass: TokenInterceptor,
    multi: true
};

此解决方案来自Angular 5和HTTPClient.如果您仅需要Angular 2的解决方案,请告诉我,我会将其发布给您.

This solution fro Angular 5 and HTTPClient. If you need solution for only Angular 2 let me know, I will post that to you.

这篇关于Angular 2+中的Web令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 02:22