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
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
localStorage.setItem('token', response.access_token);
This is how I did it with Angular 5:
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 });
}
}
My Login Component:
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);
});
}
}
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
};
This solution fro Angular 5 and HTTPClient. If you need solution for only Angular 2 let me know, I will post that to you.
回答2:
Store the token you are receiving in the local storage of the web browser and use an http interceptor to remove the token from all responses and add the token to all requests.
回答3:
Using NgCookie
module you may set like:
$cookies.put("token","your_response_val");
After that for further use.... $cookies.get ()