1

问题:我如何调用 firestore 并使用从 firestore 返回的有效负载解决我的路由器守卫?

问题:我的路由解析保护没有得到解决,即使来自 firestore 的值被返回并被定义。

import {
  ActivatedRouteSnapshot,
  Resolve,
  RouterStateSnapshot,
} from '@angular/router';
import { AngularFirestore } from 'angularfire2/firestore';
import { Observable } from 'rxjs';
import { Injectable } from '@angular/core';
import { map } from 'rxjs/operators';


@Injectable()
export class RouteResolve implements Resolve<any> {
  constructor(private db: AngularFirestore) {
  }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> {
    return this.db
               .collection('routes')
               .doc('work')
               .valueChanges()
               .pipe(
                 map((item) => {
                   if (item) {
                     console.log('items', item) // this logs just fine.
                     return item; // this doesen't resolve the router guard.
                   }
                 }));
  }
}

一切正常,但已完成解决。如果我只返回 true,则解析按预期工作。

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
  return true; // this will resolve just fine
}
4

1 回答 1

2

添加pipe(first())到您的valueChanges()可观察对象。Angular 路由器一直等到 observable 完成,这样做可以确保 observable 在第一次值更改后完成。

return this.db
           .collection('routes')
           .doc('work')
           .valueChanges()
           .pipe(first())
           .pipe(
             map((item) => {
               if (item) {
                 console.log('items', item) // this logs just fine.
                 return item; // this doesen't resolve the router guard.
               }
             }));
于 2018-08-04T05:40:47.533 回答