4

I'm pretty new to Angular. I am using Angular 6 with NGXS for state management.

My NGXS store has a user reducer whose interface is

/* src/app/store/models/user.model.ts */
export interface User {
    serverToken? : string;
    // and other unrelated stuff
}

I would like to use serverToken in Authorization header in a HttpInterceptor.

This is my current HttpInterceptor codes

import {Store, Select} from '@ngxs/store';
import {Injectable} from '@angular/core';
import {HttpInterceptor, HttpHandler, HttpRequest, HttpEvent} from '@angular/common/http';

import {Observable} from 'rxjs';
import {User} from '../store/models/user.model';

@Injectable()
export class ApiInterceptor implements HttpInterceptor {
    constructor(private store : Store) {}
    @Select()user$ : Observable < User >;

    intercept(req : HttpRequest < any >, next : HttpHandler) : Observable < HttpEvent < any >> {
        let options = {
            url: `https://base-url.com/api/${req.url}`
        };

        const serverToken = '???';
        if (serverToken) // if not empty
            options = {
                ...options,
                headers: req
                    .headers
                    .set('Authorization', `JWT ${serverToken}`)
            }

        const duplicate = req.clone(options);

        return next.handle(duplicate);
    }
}

so my question is: How to properly and elegantly use the user$ observable to get the serverToken and use it in HttpInterceptor if serverToken is not empty?

4

2 に答える 2