N
N
Nikolay Semenov2018-09-12 18:59:34
JavaScript
Nikolay Semenov, 2018-09-12 18:59:34

How to get a token from a state?

There is this class in side effects:

import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import { Actions, Effect } from "@ngrx/effects";
import { Store } from "@ngrx/store";
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { switchMap, map } from "rxjs/operators";

import * as fromRoot from "../../../store/root.reducers";
import * as LoggedUserActions from "./logged-user.actions";

@Injectable()
export class LoggedUserEffects {
  // headers: any = new HttpHeaders().set(
  //   "Authorization",
  //   "bearer " + this.store.select(fromRoot.getToken)
  // );
  headers: any;
  constructor(
    private actions$: Actions,
    private store: Store<fromRoot.State>,
    private httpClient: HttpClient
  ) {
    this.headers = new HttpHeaders().set(
      "Authorization",
      "bearer " + this.store.select(fromRoot.getToken)
    );
  }

  @Effect()
  userTransactionFetch = this.actions$
    .ofType(LoggedUserActions.FETCH_USER_TRANSACTION)
    .pipe(
      switchMap(() => {
        console.log(this.headers);
        return this.httpClient.get(
          "http://&&&&&&&:3001/api/protected/transactions",
          this.headers
        );
      }),
      map(transactions => {
        console.log(transactions);
        return {
          type: LoggedUserActions.SET_USER_TRANSACTION,
          payload: transactions
        };
      })
    );
}

the request does not go through, I suspect that due to the fact that the token is passed in the form of bearer [object Object]:
HttpHeaders {normalizedNames: Map(0), lazyUpdate: Array(1), headers: Map(0), lazyInit: HttpHeaders}
headers: Map(0) {}
lazyInit: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}
lazyUpdate: Array(1)
0:
name: "Authorization"
op: "s"
value: "bearer [object Object]"
__proto__: Object
length: 1
__proto__: Array(0)
normalizedNames: Map(0) {}
__proto__: Object

Colleagues, please tell me how to fix

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dasha Tsiklauri, 2018-09-12
@dasha_programmist

this.store.select(fromRoot.getToken)
returns observable and you need string

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question