Search code examples
angulartypescriptionic-frameworkionic4angular-canload

Ionic Auth Gaurd canLoad based on public boolean array


Situation: I'm busy developing an online course where the user has to go through a series of pages in order, but I want to keep them from navigating to other pages. If they attempt to, the current page just loads again.

My idea: I created a public boolean array that keeps track of the users' progress (example below):

progress: [boolean, boolean, boolean] = [true, false, false];

End of Page 1:
progress[0] = false;
progress[1] = true;
End of Page 2:
progress[1] = false;
progress[2] = true;

My question is: How can I use the auth guard, canLoad, to prohibit the user from accessing any other pages based on the progress array?

I have a lot of pages and would love to perform the check using one Auth Gaurd and not create a guard for every page.


Solution

  • Hard to give you exact code, but below is somewhat naive how I would do it:

    Inside a shared provider available to all your pages create an Object to track progress:

    public progress: {
         pageRoutePathName1: boolean,
         pageRoutePathName2: boolean,
    }
    

    Basically object's properties should equal your route's path value

    Then just update the state of the object's booleans similar to what you had in mind.

    Import such shared provider into your load guard and leverage the object for canLoad method:

    canLoad(route: Route, segments: UrlSegment[]): Promise<boolean> | boolean {
    
        if (this.sharedProvider.progress[route.path] === true) {
            return true
        } else {
            return false
        }
    
    }