3

I have a component that resolves data from a route when loaded.

My challenge is, whenever the data being rendered by the component changes, the component doesn't get updated unless I refresh the page, or switch to another route and back.

I understand this is because the data only gets resolved when the route is visited.

Is there a way around this such that I can subscribe to changes on the resolved data ?

Below are the relevant blocks of code.

routes.ts

{
    path: 'user-information',
    component: UserInformationComponent,
    resolve: { userData: UserDataResolver }
}

resolver.ts

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

  constructor(
    private userService: UserService
  ) {};

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<IUser> {
   return this.userService.currentUser().first();
  };
};

user.component.ts

loadUserData() {
  this.route.data.subscribe(
    data  => this.userData = data,
    error => this.updateForm.disable()
  );
};
mfalade
  • 1,647
  • 2
  • 17
  • 16

1 Answers1

1

Resolvers only allow to return a single value or object. You should be able to wrap this.userService.currentUser() in a Promise (or another Observable) and return that:

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<IUser> {
 return Promise.resolve(this.userService.currentUser());
};

You should then be able to 'rehydrate' your Observable in the component's code:

loadUserData() {
  this.route.data
    .mergeMap(data => userData)
    .subscribe(
      userData => this.userData = userData,
      error => this.updateForm.disable()
    );
  };
}

I can't test it right away, but I'm confident this works.

j2L4e
  • 6,914
  • 34
  • 40