Angular 4 load data before initialize the application

celsomtrindade picture celsomtrindade · Aug 9, 2017 · Viewed 10.5k times · Source

I'm trying to load some data before my application starts. The reason why I need to do it, is because some of the menu has restricted access based on some user condition, for example, based on the user location.

So if the user doesn't have a location yet or it's location isn't enabled to access certain view, I need to block it.


I tried to use Angular Resolve method, without success, this is what I did:

Resolve guard

// The apiService is my own service to make http calls to the server.
@Injectable()
export class AppResolveGuard implements Resolve<any> {
    constructor(
        private _api: ApiService,
        private _store: Store<IStoreInterface>,
    ) { }

    resolve(): any {
        return this._api.apiGet('loadData').subscribe(response => {
            this._store.dispatch({
                type: USER_FETCH_DATA,
                payload: response.usuario
            });

            return response;
        });
    }
}

Routing

export const routing = [
    {
        path: '', component: AppComponent, canActivateChild: [AuthGuard], resolve: {app: AppResolveGuard},
        children: [
            { path: 'home', component: HomeComponent },
            { path: 'company', canActivate: [LocationGuard], component: CompanyComponent },
        ]
    }
];

The AuthGuard is just going to check for a valid cookie session.

As you can see, the routing I'm trying to block access is the company routing. I'm able to prevent access when I first load another page, for example, if the first access is to the page home and then I navigate to the page company the validation works fine, because the user data and location is already avaliable.

However, if the first access is to the page company, it will block all users to navigate there, because at the time the LocationGuard try to validate the user location, the data isn't avaliable yet.

I also tried to replace Resolve with CanActivate, but it never enables the view after the data is avaliable, it stays on a blank page.

Answer

DeborahK picture DeborahK · Aug 9, 2017

A few things ...

Pre-fetching data before a page loads is a great use of a resolver.

Preventing access to a route is a great use of CanActivate.

Note however that the resolver only works AFTER all guards are checked. So your code will attempt to run the CanActivate before running the resolver.

enter image description here