1
votes

In my Angular (8) application want to prepopulate couple of fields from service (DB). use case: want prepopulate Address, Apartrment etc from DB, against respective pin/zip code.and getting this zip code from another service

I tried to use Resolver

Router:

const routes: Routes = [
{
  path: 'my-form',
  component: MyFormComponent,
  resolve: { managers: ManagerResolver, locationTrack: LocationTrackResolver,savedAddress: AddressResolver}
},

in my component

this.managers= this.route.snapshot.data.managers;
    this.locationTrack = this.route.snapshot.data.locationTrack;
 this.savedAddress = this.route.snapshot.data.savedAddress;

And the address Resolver: here one subscriber to get the pin code based on location and inside the subscriber another Observable to get the data.

@Injectable()
export class AddressResolver implements Resolve<Observable<PatientAddress>> {

   savedAddress: Observable<PatientAddress>;

  constructor(private addressService: AddressService, private locationMapService: LocationMapService) { }
  resolve(route: ActivatedRouteSnapshot): Observable<PatientAddress> {

    this.locationMapService.getLocation().subscribe(location => {

      this.savedAddress = this.addressService.getLastSavedAddressByPinCode(location.postal);
    });
    return this.savedAddress;
  }
}
1

1 Answers

2
votes

Observable is asynchronous so returning this.savedAddress outside subscribe will be undefied, Use switchMap to return inner observable like this

Try this:

   @Injectable()
    export class AddressResolver implements Resolve<Observable<PatientAddress>> {

      savedAddress: Observable<PatientAddress>;

      constructor(private addressService: AddressService, private locationMapService: LocationMapService) { }

      resolve(route: ActivatedRouteSnapshot): Observable<PatientAddress> {
       this.savedAddress = this.locationMapService.getLocation().pipe(switchMap(location => 
       this.addressService.getLastSavedAddressByPinCode(location.postal)));
       return this.savedAddress;
   }
 }