Проблема с заголовком Angular 2 Observable JWT

#angular #angular2-observables

#angular #angular2-наблюдаемые

Вопрос:

У меня странная проблема. Мне нужно выполнить успешный вход в систему, затем сохранить JWT, после чего мне нужно выполнить другой 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 amp;amp; 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 не суммируется в заголовке по моему второму запросу.

Комментарии:

1. Здесь та же проблема, вы нашли решение ? 🙂

2. Да, и я был неправ. Это возврат обещания с использованием Rxjs. Просто следуйте методу..