2

I am new to angular, so I though of using firebase for storing user tokens which will be accessed on calling an interceptor for modifying requests headers.

I have added firebase function in the constructor and HttpHandler function separately,

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    private token: any = null;

    constructor() {
        firebase.database().ref(`currentUserDetails/${localStorage.getItem('sn')}`).once('value', (snap) => {
            if(snap.exists()){
                this.token = snap.val().token;    
            }
        });
    }

    intercept(request: HttpRequest<any>, next: HttpHandler):  Observable<HttpEvent<any>> {
        if(this.token) {
            request = request.clone({
                setHeaders: {
                    Authorization: this.token
                }
            });
        }
        console.log(this.token) // this is null
        return next.handle(request)
    }

}

The problem is that the intercept function executes before complete execution of constructor function. So, this.token is null.

I have tried using callback function, have tried async await function and also, I have tried the solution given in stack overflow which is not succeeding.

Is there any solution to solve this issue?

Thananjaya S
  • 1,451
  • 4
  • 18
  • 31

1 Answers1

0

Due to the asynchronous nature of your once() call, which returns a promise, I would turn it into an observable and handle the data-flow inside the intercept like this:



import { from } from 'rxjs';
import { mergeMap } from 'rxjs/operators';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    private token: any = null;
    private token$: Observable<any>;

    constructor() {
        this.token$ = from(firebase.database().ref(`currentUserDetails/${localStorage.getItem('sn')}`).once('value', (snap) => {
            if (snap.exists()) {
                this.token = snap.val().token;
            }
        }));
    }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        this.token$.mergeMap(
            token => {
                if (token) {
                    request = request.clone({
                        setHeaders: {
                            Authorization: this.token
                        }
                    });
                }
                return next.handle(request)
            }
        )
    }

}

Inspiration from https://medium.com/@danielcrisp/async-http-interceptors-with-angular-4-3-9e6e795da562

Linh
  • 418
  • 4
  • 9