Използвам Angular и Firestore. Проверявам Firestore за стойност в моята охрана на маршрута.
Открих, че при опресняване на страницата тя се връща като недефинирана. Въпреки това, ако просто кодирам твърдо връщане на 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;
}
}