1

Trying to get a firebase token from FirebaseAuth.user.getIdToken(). This is for a school project. The reason I post this question mainly is because I notice many solutions are out of date it seems to me.

Convert Promise to Observable

https://gist.github.com/danielcrisp/ced7d092b07efa609285ba5f0823ca60

https://github.com/codediodeio/angular-firebase-stripe/blob/master/src/app/core/token.interceptor.ts

I tried a few of the solutions provided in the links above and eventually came to this code. But it is still not working. mergeMap expects a token and an index.

error I get on the line mergeMap((token: any, index: number) => {

Error:(27, 20) TS2345: Argument of type '(token: any, index: number) => HttpRequest' is not assignable to parameter of type '(value: any, index: number) => ObservableInput'. Type 'HttpRequest' is not assignable to type 'ObservableInput'. Property '[Symbol.iterator]' is missing in type 'HttpRequest' but required in type 'Iterable'.

import { Injectable } from '@angular/core';
import {HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpClient} from '@angular/common/http';
import {from, Observable} from 'rxjs';
import {AuthService} from '../services/auth.service';
import {FirebaseAuth} from '@angular/fire';
import {User} from 'firebase';
import {mergeMap, switchMap} from 'rxjs/operators';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  user: User;
  subscribe_firebase_user;

  constructor(private http: HttpClient, private fireAuth: FirebaseAuth) {
    this.user = fireAuth.currentUser;
    this.subscribe_firebase_user = this.fireAuth.onAuthStateChanged(a => {
      this.user = a;

    });
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // add authorization header with jwt token if available
    const observable = from(this.user.getIdToken());
    if (this.user !== null) {
      return observable.pipe(
          mergeMap((token: any, index: number) => {
          request = request.clone({
              setHeaders: {
                Authorization: `Bearer ${token}`
              }}
            );
            return request;
          }

      ));

    }

    return next.handle(request);
  }
}

From this I expect the token to be loaded in and then the request is send to the server.

Thx for the help in advance.

G. Juwot
  • 191
  • 1
  • 7

0 Answers0