Question: How can my call to firestore and resolve my router guard with the payload returned from firestore?
Problem: My route resolve guard does not get resolved, even though the value from firestore is being returned and is defined.
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.
}
}));
}
}
Everything is working but the completed resolve. If i just return true, the resolve works as intended.
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
return true; // this will resolve just fine
}
Add pipe(first())
to your valueChanges()
observable. Angular router waits until the observable is complete, and doing this ensures that observable gets completed after the first value change.
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.
}
}));