0

canActivate is added on admin Page.

In the home page we have link admin.

The problem here is on the first click , Though I'm admin I'm not routed to the page But on the second click, I'm routed.

Why is this happening ?

dataservice.ts

 getUsersData() : Observable<Object[]>  {
        return this.http.get<Object[]>("https://holder.com/users")

   }

authservice

admin : boolean
constructor(private dataService : DataService) { }

isAdmin() {
   this.dataService.getusersData().subscribe(data => {
           if(data.includes("Joseph")) {
             return this.admin = true ;
           } 
           else {
             return this.admin = false ;
           }
})
return this.admin
}

authguardservice

 canActivate(route : ActivatedRouteSnapshot,
                state : RouterStateSnapshot) : Observable<boolean> | Promise<boolean> | boolean {
            const isAdmin = this.authService.isAdmin()

                   if(isAdmin) {

                       return true
                   }
                   else {

                       this.router.navigate(['/'])
                   }


}

Shivaay
  • 51
  • 1
  • 10
  • You need to return an observable: Also read: https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call Welcome to the asynchronous world! – AT82 Sep 17 '19 at 13:21

1 Answers1

0

You can simplify this a lot by ignoring the subscription in the service and return the observable. Because auth guard can expect observables and subscribe to it internally

isAdmin(): Observable < boolean > {
    this.dataService.getusersData().pipe(
        map(data => data.includes("Joseph"))
    )
    return this.admin
}


canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable < boolean > | Promise < boolean > | boolean {
    return this.authService.isAdmin()
}
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80