If you need to execute code (such as getting data) before loading a route, you can use a route resolver service.
Here is an example:
import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { ProductResolved } from './product';
import { ProductService } from './product.service';
@Injectable({
providedIn: 'root'
})
export class ProductResolver implements Resolve<ProductResolved> {
constructor(private productService: ProductService) { }
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<ProductResolved> {
const id = route.paramMap.get('id');
if (isNaN(+id)) {
const message = `Product id was not a number: ${id}`;
console.error(message);
return of({ product: null, error: message });
}
return this.productService.getProduct(+id)
.pipe(
map(product => ({ product: product })),
catchError(error => {
const message = `Retrieval error: ${error}`;
console.error(message);
return of({ product: null, error: message });
})
);
}
}
But in your case, it sounds like you need to run code on application initialization. If that is the case, the info here may help: https://www.intertech.com/Blog/angular-4-tutorial-run-code-during-app-initialization/