私は奇妙な問題を抱えています。ログインに成功してから JWT を保存する必要があります。その後、新しいヘッダーを使用して別の HTTP リクエストを作成する必要があります。これには、ユーザーの詳細を取得するための認証として JWT が含まれます。残念ながら、私の 2 番目の 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 が 2 番目のリクエストのヘッダーに追加されません。