Я использую angular и firestore. Я проверяю firestore на наличие значения внутри моей защиты маршрута.
Я обнаружил, что при обновлении страницы он возвращается как undefined. Однако, если я просто жестко запрограммирую возврат true или false, это сработает.
Любые журналы в моем операторе if всегда возвращаются правильно, но, похоже, по какой-то причине моя глобальная переменная не обновляется.
Если я использую навигацию по сайту, чтобы вернуться к корню и перемещаться по моему сайту, он работает правильно. Однако, когда я обновляю страницу, она возвращается как неопределенная.
Может ли это быть проблемой области видимости?
Защита маршрута
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, RouterStateSnapshot, CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';
import { Subscription } from 'rxjs/Subscription';
//testing
import { Observable } from 'rxjs/Observable';
import { AngularFireAuth } from 'angularfire2/auth';
@Injectable()
export class CheckBillingService implements CanActivate {
private _subscription: Subscription;
private userBillingDocRef: AngularFirestoreDocument<any>;
userBilling: Observable<any>;
public activeAccount:Observable<boolean>
constructor(private authService: AuthService,
private router: Router,
private auth: AngularFireAuth,
private readonly afs: AngularFirestore) {}
canActivate(): Observable<boolean> {
this.authService.user.subscribe((user) => {
if (user) {
var userId = user.uid;
this.userBillingDocRef = this.afs.doc('user_billing/${userId}');
this.userBilling = this.userBillingDocRef.snapshotChanges();
this.userBilling.subscribe((value) => {
const data = value.payload.data();
if (data.account_status == "Active") {
this.activeAccount = Observable.of(true);
console.log('inside if statement for active = ', this.activeAccount);
} else {
this.activeAccount = Observable.of(false);
console.log('inside if statement for not active = ', this.activeAccount);
this.router.navigate(['resubscribe']);
return Observable.of(false);
}
console.log('userBilling.subscribe = ', this.activeAccount);
});
console.log('just outside userBilling.subscribe = ', this.activeAccount);
}
});
// When refreshig my page, this returns as undefined.
// If I navigate to the correct page and work my way through the site it works fine
// However, refresh returns undefined.
console.log('out of auth = ', this.activeAccount);
return this.activeAccount;
}
}