How to trigger route resolver manually

偶尔善良 提交于 2019-12-05 00:44:47

I agree with "Woot", but if you want to trigger the resolver again, go to your routing module and add

runGuardsAndResolvers: "always"

Now you can navigate on the same page again an the resolver will run again. But be aware only the resolver will run again, no other lifecyle, like "ngOnInit".

Example according to you code

app-routing.component.ts

{
  path: 'users/:id',
  component: UserComponent,
  resolve: {user: UsersService},
  children: [
    {path: '', pathMatch: 'full', redirectTo: 'account'},
    {path: 'account', component: UserAccountComponent, runGuardsAndResolvers: "always"},
    {path: 'sites', component: UserSitesComponent}
  ]
}

Now if you route to the same page again the subscription on your user-account.component.ts will be triggered again

Typically you wouldn't want to trigger a route resolver manually.

Since your resolver looks to be part of your service and all it does is call this.getUser(id) you could easily call it after a change is made.

What I would do in this scenario is have my service injected into my class, and then after the action that updates the user call the this.getUser(id).

Possible implementation

export class UserAccountComponent implements OnInit {
  userId: number;
  constructor(private route: ActivatedRoute, private userService: UserService) {}

  ngOnInit() {
    this.route.params.pipe(
      do((params) => {
        this.userId = +params['id'];
      }),
      take(1)
    );
  }

  doSomeChange() {
    // this will execute a change and update the user.
    this.userService.get(this.userId);
  }
}

Note: I am using code that is dependent on rxjs 5.5 Additionally your service must be included in your providers for this to work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!