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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…