次のコードは、最後の if ステートメントが true の場合に正しく機能します。最後の if ステートメントが false の場合、要求されたルートを解決しません。awaits と asyncs を追加してみました。ブール値で await を返す別の関数にコードを移動しようとしましたが、必要なときにルートを解決するために何も機能していません。設定へのリダイレクトを拒否する必要がある場合は常に機能します。
If ステートメント
if(moduleSnapshot.size >= planLimit) {
this.toast.info(`You've reached your plan maximum, upgrade to add more ${mod}.`, 'Plan Maximum');
this.router.navigateByUrl('/settings/profile/subscription');
return false;
}
return true;
完全なルーター ガード
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { ToastrService } from 'ngx-toastr';
import { AngularFirestore } from '@angular/fire/firestore';
import { AuthService } from '../services/auth/auth.service';
import { SubscriptionsService } from '../services/subscriptions/subscriptions.service';
@Injectable({
providedIn: 'root'
})
export class SubscriptionGuard implements CanActivate {
constructor( private router: Router, private toast: ToastrService, private authService: AuthService, private subscriptionService: SubscriptionsService, private afs: AngularFirestore ) { }
canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): any {
this.authService.userData.subscribe((observer1) => {
if(observer1) {
let subscriptions = this.subscriptionService.fetchUserSubscription(observer1.uid);
subscriptions.onSnapshot((observer:any) => {
observer.forEach((subscription:any) => {
if(subscription.exists) {
this.authService.allUserData.subscribe( async(userDataObserver:any) => {
let mod:string = state.url.split('/')[1];
await this.subscriptionService.fetchPlan(subscription.data().productID).then((plan:any) => {
let planLimit:number = parseInt(plan.metadata[mod]);
let companyUid:string = userDataObserver.companies[0].company;
this.afs.collection('companies').doc(companyUid).collection(mod).ref.get().then((moduleSnapshot:any) => {
if(moduleSnapshot.size >= planLimit) {
this.toast.info(`You've reached your plan maximum, upgrade to add more ${mod}.`, 'Plan Maximum');
this.router.navigateByUrl('/settings/profile/subscription');
return false;
}
console.log('Plan max not met, should resolve');
return true;
});
});
});
}
});
});
}
});
}
}