0

我有一个 Angular guard,它使用来自注入服务的数据来确定是否可以访问路由,如下所示:

@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;
            })
        );
    }    
}

服务,抽象了不重要的东西,看起来像这样:

@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);
            });
    }
}

这是控制台日志的序列:在守卫 ctor 中来自守卫:未定义在数据服务 ctor 数据到达:{...}

很明显,守卫在数据服务之前被实例化。我怎样才能防止这种情况?两者都在根目录中提供。

4

0 回答 0