Is there a way to resolve data for an Angular 4 service before it's injected into a component?

Viewed 1720

I'm new to Angular 2/4, so please forgive my ignorance. I have a service that I want to inject into various components, but this service uses meta data that needs to be retrieved from the server first. I'd like to know if there's a way to ensure the data for the service is resolved before the service gets injected into the components.

I read a little about route guards which sounds similar to what I'm looking for, but I don't think that applies to my problem since the service itself doesn't have a route.

1 Answers

Resolve in Angular 2/4 is used to get data before we activate a route and component.

UserResolve service gets data from the server.

import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot} from '@angular/router';
import { UserService } from '../services/user.service';

@Injectable()
export class UserResolve implements Resolve<any> {

  constructor(private service: UserService) {}

  resolve(route: ActivatedRouteSnapshot) {
    return this.service.getUser().then(user => user);
  }

}

Note: Import the "UserResolve" in your module and use it in providers (shown below).

.......
import { UserService } from '../services/user.service';
import { UserResolve } from './user.resolve';

@NgModule({
  imports: [ ... ],
  declarations: [HomeComponent, AboutComponent, AboutUserComponent],
  providers: [UserService, UserResolve]
})
export class UserModule {  }

Use it in router module to call service (resolves data) before the component loads.

 const aboutRoutes: Routes = [
      {
        path: '',
        component: HomeComponent,
        children: [
          {
            path: '',
            component: AboutComponent,
            resolve: {
              user: UserResolve
            }
          },
          {
            path: 'user',
            component: AboutUserComponent
          }
        ]
     }
]

Thank You...

Related