-2

We are building an angular application. Which will be behind and authentication server. So we are not building any login forms. We have rest endpoint which will give me currently logged in user info and their permissions to view pages in angular for which I have created guards. I written a sevice to fetch the details as well.

Now My problem is app component is loaded before I fetch the details and display content to user.

What is recommended way for these situations?

user6f6e65
  • 146
  • 9
Mahesh B
  • 143
  • 2
  • 13
  • I am not sure why my question got negative. Is this not a write question to ask or is it wrong place ? – Mahesh B Nov 28 '18 at 21:14
  • I have implemented the same in my project . APP_INITIALIZER is your saviour here.Go through the link : https://stackoverflow.com/questions/49707830/angular-how-to-correctly-implement-app-initializer . . If you face any issue do let us know with stackBlitz . – programoholic Nov 28 '18 at 22:01
  • @programoholic yes I tried with APP_INITIALIZER but I missed that factory should have promise. I made changes now working. – Mahesh B Nov 29 '18 at 14:51

1 Answers1

1

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/

DeborahK
  • 57,520
  • 12
  • 104
  • 129
  • I tried with useFactory but ddint worked as expected after your suggested site. I figured out that factory should have promise to be sent. Now working as expected. Thank you so much. – Mahesh B Nov 29 '18 at 14:49