Oscar
Oscar

Reputation: 43

CanLoad, Lazy modules and take(1)

I'm protecting a lazy module with a Guard using CanLoad.

I'm recovering the status of my ngrx store, and checking if the user is authenticated.

Here is my code in my auth-guard.service.ts:

canLoad() {
    return this.store.pipe(
        select('auth'),
        take(1),
        map(
            (authState: fromAuth.State) => {
                if (authState.authenticated) {
                    return true;
                } else {
                    this.router.navigate(['/auth/signin']);
                    return false;
                }
            }
        ))
}

This code is OK. All works as expected.

But the question is... Why I need to use take(1) to make this works? If I remove the take(1), this guard don't works properly.

Upvotes: 2

Views: 264

Answers (1)

J. Knabenschuh
J. Knabenschuh

Reputation: 765

It will only work with take(1) because without the observable wont complete at this time and canLoad waits until the observable completes.

See http://reactivex.io/documentation/operators/take.html the take will build an new observable take x items from its source and after it will complete and ignore further items.

Upvotes: 1

Related Questions