jack
jack

Reputation: 183

ngOnInit is calling before resolver data is ready

I have a resolve that is calling getSchools() from service

resolver.ts

export abstract class APIResolverService implements Resolve<any> {
          constructor(readonly dropdownService:DropDownOptionsService,readonly route:ActivatedRoute) { }
          abstract resolve();
        }


export class APISchoolsresolve extends APIResolverService{

      resolve(){
        this.route.queryParams.subscribe(params => {
          let district = params['district'];
          return this.dropdownService.getSchools(district);   
        })
      }

My Service

async getSchools(districtID:number){
    return await this.http.get<ISchool[]>(`api/GetSchools/` + districtID).toPromise();
  }

My Component

this.activatedRoute.data.subscribe((data) =>{

      console.log(data);
    })

my data in component is undefined as it is being called before my resolver get data.

How do I fix this?

Upvotes: 0

Views: 1172

Answers (1)

JB Nizet
JB Nizet

Reputation: 691835

Your resolve method doesn't return anything. So the router doesn't wait for anything to be resolved: what could it possibly subscribe to or await for?

Also, the resolve method takes an ActivatedRouteSnapshot. That's where you should take the districtID from.

Here's what the resolver should look like:

export class APISchoolsresolve implements Resolve<Array<ISchool>> {
  constructor(private dropdownService: DropdownService) { }

  resolve(route: ActivatedRouteSnapshot): Promise<Array<ISchool>> {
    return this.dropdownService.getSchools(+route.paramMap.get('district'));
  }
}

Upvotes: 2

Related Questions