0
votes

I'm literally going crazy trying to use a Resolver in Angular 6.

My Resolver, working version:

    @Injectable()
export class MyResolver implements Resolve<boolean> {
    constructor() {
    }

    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
        return true;
    }

I inject it like this in my routing:

path: "secure",
    component: SecureComponent,
    canActivate: [AuthGuard],
    canActivateChild: [AuthGuard],
    resolve: {
        myValue: MyResolver
    }

This works properly, the component constructor is fired and I can retrieve the myValue from the route.

But as soon as I change my resolver to:

return Observable.create(true);

Or any code that returns an Observable instead of a plain value the constructor of the component isn't fired anymore, and I get a blank page at my route. The resolver code still runs in its entirety.

I verified the constructor not being fired by placing a console.log("foo") at the very first line of the constructor, and it is not called.

So I can't understand why I can't output an observable from my resolver. The whole point of the resolvers is to resolve deferred values (thus returning observables).

What am I doing wrong?

2
create a stackblitz to show ur errorashfaq.p
I don't have any error to show, just a blank page and the component not being activated.Matteo Mosca
i mean show us your issue by representing it. that way we can help you better. Bcoz otherwsie, returning observable should workashfaq.p
False alarm. Does not work even with toPromise. Must keep looking.Matteo Mosca
I am using it with observalbes and it works just fineashfaq.p

2 Answers

3
votes

I think the problem is that Observable.create does not complete the observable stream. Thus subscribing in your route does not emit anything. You should try something like this:

import { of } from 'rxjs/observable/of';

return of(true);

This will return a complete observable. Or you could also do:

return Observable.create((observer) => {
  observer.next(true);
  observer.complete();
    });

Let me know..

1
votes

Observable.create accepts a function as an argument.

Observable.create(true) will result in error on subscription. The component isn't instantiated because there is navigation error that wasn't caught.

If a resolver is supposed to return existing value, this should be done as original code shows:

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    return true;
}