jxycms
12/20/2019 - 6:00 AM

angular resolver

**** send data to component via resolver

1. create resolver file -- ate-resolver.service.ts

import {Injectable, Inject} from '@angular/core';
import {Resolve, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router';
import { Observable } from 'rxjs';
import { APP_CONFIG, IAppConfig } from '../../config/app.config';
import { DataContextService } from 'src/app/service/datacontext.service';

// version 1
@Injectable()
export class ATEResolver implements Resolve<Promise<any>> {
    constructor(private dataContextService: DataContextService, @Inject(APP_CONFIG) private config: IAppConfig) {
    }
    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        console.log('ATE Resolver ');
        const promise = new Promise((resolve, reject) => {
            const url = this.config.apiEndpoint + '/ReferenceData/CancellationReasons';
            this.dataContextService.httpGet(url).subscribe(
                rs => {
                    console.log(rs);
                    resolve({ 'CancellationReasons' : rs });
                },
                err => console.log(err)
            );
        });
        return promise;
    }
}

// version 2
@Injectable()
export class StaffResolverService implements Resolve<SimpleStaff[]> {
  constructor(private lookupService: LookupService) {}
  resolve(): Observable<SimpleStaff[]> {
      return this.lookupService.getStaffList();
  }
}

2. add to route

{
  path: 'home',
  component: DashboardComponent,
  resolve: {
    authSettings: AuthSettingsResolverService,
    //staff: StaffResolverService,
    processTypes: ProcessTypesResolverService,
    //schools: SchoolsResolverService,
    
  }
}

3. get data in component

private route: ActivatedRoute

// version 1
this.route.data.subscribe(data => {
    const { staff } = data;
});

// version 2
this.allStaff = this.route.snapshot.data["staff"];