如何从AngularFirestore获得可观察的收益并解决我的路由器防护

时间:2018-08-04 05:33:15

标签: angular google-cloud-firestore angular2-observables resolver angular-router-guards

问题:如何调用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
}

1 个答案:

答案 0 :(得分:1)

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

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