How to refresh a route's resolved data

2019-04-19 08:03发布

Consider the following route configuration:

const routes: Routes = [
  {
    path: '',
    component: AppComponent,
    resolve: {
      app: AppResolver
    },
    children: [
      {
        path: 'user/:uid',
        resolve: {
          user: UserResolver
        },
        children: [
          {
            path: '',
            component: ViewUserComponent
          },
          {
            path: 'edit',
            component: EditUserComponent
          }
        ]
      }
    ]
  }
];

The user data are retrieved by UserResolver for any children of route /user/:uid. Using this data, a user profile can be viewed by navigating to /user/:uid and then edited by navigating to /user/:uid/edit. Upon a successful edit, one would expect to be redirected to the user's updated profile (/user/:uid).

However, both the view and edit page being children of the resolved route, the resolver is not triggered when navigating from one to the other.

Consequently, when navigating back from the edit component to the view component, the data displayed is still the old, non-updated one.

Would there be any way to invalidate the resolved user data to force the resolver to fetch it again from the server? Or is there any other way to achieve that kind of result?

The app data being unchanged, we shouldn't have to reload it.

4条回答
beautiful°
2楼-- · 2019-04-19 08:40

You can try something like this:

constructor(private activatedRoute: ActivatedRoute) {
  this.activatedRoute.parent.data.subscribe(data => {
    this.profile = data.profile;
  });
}

updateProfile(newProfile) {
  (this.activatedRoute.parent.data as BehaviorSubject<any>).next({profile: newProfile});
}
查看更多
仙女界的扛把子
3楼-- · 2019-04-19 08:42

By above way i can call the resolver. But it not change data which comes from my backend server so i got one solution i call my service method again in success part and got new changed data from backend server.

查看更多
再贱就再见
4楼-- · 2019-04-19 08:59

I've tested the solution 'runGuardsAndResolvers', it works for my use case, the resolver is called at each sub-page changes.

It is only adding this option the part of your routes that you want behave this way.

export const ROUTES: any = [
  {
    path: 'project/:name',
    runGuardsAndResolvers: "always",
    component: ProjectComponent,
    resolve: { project: ProjectResolver },
    children: [
      ...
查看更多
啃猪蹄的小仙女
5楼-- · 2019-04-19 09:03

There is a parameter you can use in your route configuration called 'runGuardsAndResolvers' that will affect when the resolver runs. In this case you would want to set it to 'always'. This means that the resolver will run any time the child routes of that route change. See the route documentation for more information.

查看更多
登录 后发表回答