0

I'm using the resolve method of the Routes interface to resolve routes data from the Store (ngrx) by returning a reducer observable in the canUse method of the Resolve interface. However unlike HtppClient's http method's returned Observables, Store's returned Observable doesn't seem to work the same way.

I have a resolver class called ResolveFromStore which looks like this:

@Injectable()
export class ResolveFromStore implements Resolve<Observable<any>> {
observable:Observable<any>
constructor(
    private _store:Store<any>
) {
    // the reducer
    this.observable = this._store.select(from_store_index.getLanguage);
}
    resolve(route: ActivatedRouteSnapshot) {
              return this.observable;  
    }
}

And in my router I'm incorporating it as so:

 const routes: Routes = [{
    path: '',
    component: PostPaidPageComponent,
    children: [
        {
            path: 'treatment',
            component: TreatmentPostpaidComponent,
            resolve: {
                fromStore: resolvers.ResolveFromStore 
            }
        }...

How ever this does not seem to work with store subscription, unlike http subscription which resolve fine.
I am returning an observable in the resolve function, so what could be wrong.

TKDev
  • 493
  • 1
  • 4
  • 19

1 Answers1

3

I don't think that using a resolver is a god fit here.

When you pass an observable to the resolve function, it'll wait for that observable to complete BEFORE letting you go the requested route.

One easy fix but with a huge limit... Is to use first or take(1) on your observable. But of course, you'll get the value only once after that.

I've made a whole question asking why resolver would be useful because of that: Why would you use a resolver with Angular

maxime1992
  • 22,502
  • 10
  • 80
  • 121
  • I bascially want to move all my store subscription from the controllers to the Router's resolve array, this is since I have the same subscriber for "language" on almost all of the components, this way I reduce code repetition in my app – TKDev Jun 24 '18 at 14:02
  • using `pipe(first())` did solve my problem, but what is the difference between returning a **Store's select observable** and the **first()** that the one works and the second doesn't. Will mark your question as V if this is explained also. – TKDev Jun 24 '18 at 14:14
  • 1
    As explained, a resolver is waiting for an observable to complete before going further. You are watching something on your ngrx store, the stream is never completed. It's kept open. Using first closes the stream as soon as one value went through. That's why it's working :) – maxime1992 Jun 24 '18 at 14:16