1

I have an Angular guard that uses data from injected service to determine if a route can be accessed, like so:

@Injectable({
    providedIn: 'root'
})
export class MyGuard implements CanActivate {
    constructor(private someService: SomeService, private router: Router) { console.log('in guard ctor'); } // CONSOLE LOG

    canActivate(
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
        return this.someService.data$.pipe(
            tap(u => console.log('from guard: ', d)), // CONSOLE LOG
            map(data => {
                if (!data) {                    
                    this.router.navigate(['/whatever']);
                    return;
                }
                else
                    return true;
            },
            err => {
                this.router.navigate(['/whatever']);
                return err;
            })
        );
    }    
}

The service, with unimportant stuff abstracted, looks something like this:

@Injectable({
    providedIn: 'root'
})
export class SomeService {
    private dataSource = new BehaviorSubject<MyData>(null);
    public data$ = this.dataSource.asObservable().pipe(map(u => cloneData(u)));

    constructor(private apiService: SomeApiService,
        authorizeService: AuthorizeService) {

        authorizeService.isAuthenticated()
            .pipe(
                tap(auth => console.log('in data service ctor')), // CONSOLE LOG
                filter(x => !!x),
                mergeMap(() => apiService.get())
            )
            .subscribe(res => {
                console.log('data arrived: ', res); // CONSOLE LOG
                this.dataSource.next(res);
            });
    }
}

This is the sequence of console logs: in guard ctor from guard: undefined in data service ctor data arrived: {...}

It's obvious that the guard gets instantiated before data service. How can I prevent this? Both are provided in root.

dzenesiz
  • 1,388
  • 4
  • 27
  • 58
  • What is the question here? I don't get it.. What is the error you are getting? What bug are facing here? – Andres2142 Jul 06 '21 at 00:36
  • I thought the question to be clear - how to prevent the guard being instantiated before the service it depends on, which results in false negatives. You can see from the console logs that the guard is called before the service. – dzenesiz Jul 06 '21 at 00:45
  • It's not all in one line on desktop though... I submitted my question on a PC, mobile view puts all console logs in one line which makes things unclear. – dzenesiz Jul 06 '21 at 00:46

0 Answers0