I am making an Angular 4 web app. I need to protect my routes so I am using AuthGuard
and CanActivate
to check if the user can access a certain route.
CanActivate
first checks if the id
is in sessionStorage
else it checks my backend if the user is authorized. If I click on a project with an id
already in sessionStorage
and it goes into the checkIfIDInStorage
it works fine, however if it goes into the else and makes a call to my API it goes to the end of the function and returns false before the call returns true If I remove the return false
in canActivate
it still doesn't work. If I click on the project again after I see that it has returned true it works fine.
Console output
can activate else
before return false
in subscribe if
true
in store
Guard.ts
canActivate (route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean
{
const id = route.params.id;
if (this.checkIfIDInStorage(id)) {
console.log("checking id");
return true;
}
else {
console.log("in can activate else");
this.API.checkProjectOwnership(id).subscribe((data) =>
{
console.log("in subscribe if");
if (data.type === 'AL') {
console.log("true");
this.storeProjectID(id);
return true;
}
else {
console.log("in subscribe else ");
this.router.navigate(['/dashboard']);
}
});
}
console.log("before return false");
return false;
}
storeProjectID(id: string) {
console.log("in store");
this.session.store('id', id);
return true;
}
getProjectID() {
return this.session.retrieve('id');
}
checkIfIDInStorage(id: string) {
const storedID = this.getProjectID();
return (id === storedID);
}
API.service.ts
checkProjectOwnership(params: URLSearchParams): Observable<any> {
const URL = `${this.API}/projects/ownership?id=${params}`;
return this.auth.refreshToken()
.flatMap(() => this.authHttp.get(URL, this.headers))
.map((response: Response) => response.json())
.share()
.catch(this.handleError);
}
I was able to solve it by returning an observable.
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean
{
const id = route.params.id;
return new Observable<boolean>((observer) =>
{
if (this.checkIfIDInStorage(id)) {
observer.next(true);
observer.complete();
}
else {
const params = new URLSearchParams();
params.append('id', id);
this.API.checkProjectOwnership(id).subscribe((data) =>
{
console.log("in subscribe if");
if (data.type === 'AL') {
this.storeProjectID(id);
observer.next(true);
observer.complete();
}
else {
this.router.navigate(['/dashboard']);
observer.next(false);
observer.complete();
return false;
}
});
}
});
}
@Injectable()
export class DrawingBoardGuard implements CanActivate {
constructor( private _http: HttpClient, private _router : Router) {
}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
let url : string = 'someUrl';
return new Observable<boolean>((observer:any) => {
this._http.get(url)
.map((result) => {
if(!result.isPermitted){
this.navigateToOtherPage(...);
observer.next(false);
observer.complete();
return false;
}else {
observer.next(true);
observer.complete();
return true;
}
})
.catch(err => {
this.navigateToOtherPage(...);
return Observable.of(false);
});
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.