我有一个奇怪的问题。我需要成功登录然后保存 JWT,然后我需要使用新的 Header 发出另一个 HTTP 请求,其中包括作为授权的 JWT 以获取用户详细信息。不幸的是,在我的第二个 HTTP 请求中,我错过了 JWT。任何帮助,将不胜感激。
以下是我的代码
API服务
import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
import 'rxjs/add/observable/throw';
import { AppState } from './state.service';
@Injectable()
export class ApiService {
token: string = this._appState.get('_token');
headers: Headers = new Headers({
'Content-Type': 'application/json',
Accept: 'application/json',
'Authorization': this.token ? this.token : null
});
api_url: string = '/';
constructor(private http: Http, public _appState: AppState) {}
private getJson(response: Response) {
return response.json();
}
private checkForError(response: Response): Response {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
let error = new Error(response.statusText);
error['response'] = response;
console.error(error);
throw error;
}
}
getall(path: string): Observable<any> {
console.log('from api', this.token);
return this.http.get(`${this.api_url}${path}`, { headers: this.headers })
.map(this.checkForError)
.catch(err => Observable.throw(err))
.map(this.getJson);
}
get(path: string, query: string): Observable<any> {
return this.http.get(`${this.api_url}${path}/${query}`, { headers: this.headers })
.map(this.checkForError)
.catch(err => Observable.throw(err))
.map(this.getJson);
}
post(path: string, body): Observable<any> {
return this.http.post(
`${this.api_url}${path}`,
JSON.stringify(body),
{ headers: this.headers }
)
.map(this.checkForError)
.catch(err => Observable.throw(err))
.map(this.getJson);
}
put(path: string, query: string, body): Observable<any> {
return this.http.put(
`${this.api_url}${path}/${query}`,
JSON.stringify(body),
{ headers: this.headers }
)
.map(this.checkForError)
.catch(err => Observable.throw(err))
.map(this.getJson);
}
delete(path: string): Observable<any> {
return this.http.delete(
`${this.api_url}${path}`,
{ headers: this.headers }
)
.map(this.checkForError)
.catch(err => Observable.throw(err))
.map(this.getJson);
}
}
登录组件
import { Component, Input, OnInit, Output, EventEmitter } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { FormValidationService } from '../formValidation';
import { CredFormService } from './credForm.service';
import { AppState, GetUserService } from '../../services';
@Component({
selector: 'ce-cred-form',
styles: [require('./credForm.style.scss')],
templateUrl: './credForm.html',
providers: [FormValidationService, CredFormService]
})
export class CredFormComponent implements OnInit {
@Input() credFormType: string;
@Output() loggedIn = new EventEmitter();
public credForm: FormGroup;
public loginForm: FormGroup;
public cred_error_message = false;
public _token: string;
constructor(
private _fb: FormBuilder,
private _validationService: FormValidationService,
private _credFormService: CredFormService,
public _appState: AppState,
public _getUser: GetUserService ) {
}
ngOnInit() {
this.cred_error_message = false;
this.credForm = this._fb.group({
name: ['', [Validators.required, Validators.minLength(3)]],
email: ['', [Validators.required, this._validationService.emailValidator]],
password: ['', [Validators.required, this._validationService.passwordValidator]],
});
this.loginForm = this._fb.group({
email: ['', [Validators.required, this._validationService.emailValidator]],
password: ['', [Validators.required]]
});
}
signup() {
this._credFormService.signup(this.credForm.value)
.subscribe(
res => {
this.ngOnInit();
this.loggedIn.emit({ _token: res.token });
},
err => {
this.cred_error_message = JSON.parse(err._body).message;
});
}
login() {
this._credFormService.login(this.loginForm.value)
.subscribe(
res => {
this.ngOnInit();
// this.loggedIn.emit({ _token: res.token });
this._token = res.token;
localStorage.setItem('_token', this._token);
this._appState.set('_token', this._token);
},
err => {
this.cred_error_message = JSON.parse(err._body).message;
},
() => {
this._getUser.getUser()
.subscribe(
res => console.log(res),
err => console.log(err),
() => console.log('get user complete')
);
this.loggedIn.emit({ _token: this._token });
});
// return this._credFormService.login(this.loginForm.value)
}
}
登录服务
import { Injectable } from '@angular/core';
import { ApiService } from '../../services';
import 'rxjs/Rx';
@Injectable()
export class CredFormService {
path: string = 'auth/';
constructor( private _apiService: ApiService ) {
}
login(body) {
return this._apiService.post(this.path + 'login', body);
}
signup(body) {
return this._apiService.post(this.path + 'signup', body);
}
}
用户服务
import { Injectable } from '@angular/core';
import { ApiService } from './restful.services';
@Injectable()
export class GetUserService {
private _path: string = 'apis/user';
constructor( private _apiService: ApiService ) { }
getUser() {
return this._apiService.getall(this._path);
}
}
国家服务
import { Injectable } from '@angular/core';
export type InternalStateType = {
[key: string]: any
};
@Injectable()
export class AppState {
_state: InternalStateType = { };
constructor() {
}
// already return a clone of the current state
get state() {
return this._state = this._clone(this._state);
}
// never allow mutation
set state(value) {
throw new Error('do not mutate the `.state` directly');
}
get(prop?: any) {
// use our state getter for the clone
const state = this.state;
return state.hasOwnProperty(prop) ? state[prop] : state;
}
set(prop: string, value: any) {
// internally mutate our state
return this._state[prop] = value;
}
private _clone(object: InternalStateType) {
// simple object clone
return JSON.parse(JSON.stringify( object ));
}
}
JWT 没有在我的第二个请求的标头中添加。