Return Oberservable/Access Store Value in RouteSerializer?

26 Views Asked by At

Is there any possible way for the RouteSerializer in ngrx-router-store to return either a Promise or an Observable?

What I'm really trying to achieve is to look up some link metadata that is stored within a store. But, they only way to access store values is via this._store.select which returns an Observable. I don't see anything in the docs that allows for this return type so posting here before I scratch this approach and try something different. Just seems strange that ngrx would refuse to work with Observables in any scenario...

export class CustomSerializer implements RouterStateSerializer<RouterStateUrl> {
    serialize(routerState: RouterStateSnapshot, private _store: IAppStore): RouterStateUrl {
        let route = routerState.root;

        while (route.firstChild) {
            route = route.firstChild;
        }

        const {
            url,
            root: { queryParams },
        } = routerState;
        const { params } = route;

        // Only return an object including the URL, params and query params
        // instead of the entire snapshot
        return this._store.select( state => state.navStore.links).pipe(
            map( links => {
                const l = links.find(l => l.id === 123);
                return { url, params, queryParams, l };
            })
        );
    }
}
1

There are 1 best solutions below

1
Michael Kang On

Just subscribe to the store, and maintain links as a member variable:

export class CustomSerializer implements RouterStateSerializer<RouterStateUrl> {
    links: string[] = [];
    constructor(private store: IAppStore) {
         this._store.select( state => state.navStore.links).subscribe(t => {
            this.links = t;
         });
    }
    serialize(routerState: RouterStateSnapshot, private _store: IAppStore): RouterStateUrl {
        let route = routerState.root;

        while (route.firstChild) {
            route = route.firstChild;
        }

        const {
            url,
            root: { queryParams },
        } = routerState;
        const { params } = route;

        // Only return an object including the URL, params and query params
        // instead of the entire snapshot
        
        const l = this.links.find(l => l.id === 123);
        return { url, params, queryParams, l };
            
        
    }
}