我将 Ionic 与 Angular 一起使用。在我的一个路由守卫中,我需要查看是否创建了 Firestore 文档并为其返回一个布尔值,这需要一些时间才能从服务器获得响应,但是路由守卫不会等待该值返回并正常运行,因此页面不受保护!我怎样才能让路由守卫等待值?或者,在路由保护运行之前返回值?这是我向firestore发送请求的地方:
export class FirebaseService {
ex: Promise<boolean>;
categoryDone: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
constructor(private afs: AngularFirestore) {
this.ex = new Promise((resolve) => {
this.afs.collection('users').doc(this.user.uid).collection('categories').get().toPromise().then(
data => {
if (data.size > 0) {
resolve(true)
} else {
resolve(false)
}
}
)
})
this.ex.then(data=>{
if (data) {
this.categoryDone.next(true)
} else {
this.categoryDone.next(false)
}
})
}
这是我的路由保护代码,我将它用于我的页面:
export class CategoryDoneGuard implements CanActivate {
categoryDone: boolean;
constructor(private router: Router, private firebaseService: FirebaseService) {
this.firebaseService.categoryDone.asObservable().subscribe(
categoryDone => this.categoryDone = categoryDone
)
}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | boolean {
console.log(this.categoryDone,"Category Done VAriable in CategoryDoneGuard")
setTimeout(() => {
console.log(this.categoryDone,"Catgeory") //true because i waited 1 second
}, 1000);
if (!this.categoryDone) { //variable is undefined here
console.log('You are in InfoDoneGuard')
return true
}
this.router.navigate(['tabs/tab-profile'])
return false
}
}