How do I pass data to Angular routed components?

前端 未结 16 1297
挽巷
挽巷 2020-11-22 08:03

In one of my Angular 2 routes\'s templates (FirstComponent) I have a button

first.component.html

16条回答
  •  無奈伤痛
    2020-11-22 08:23

    One fine solution is to implement a Guard with canActivate method. In this scenario you can fetch data from a given api and let user access the component describe in the routing file. In the meantime one can set the data property of the route object and retrieve it in the component.

    Let say you have this routing conf:

    const routes: Routes = [
        { path: "/:projectName", component: ProjectComponent, canActivate: [ProjectGuard] }
    ]`
    

    in your guard file you may have:

    canActivate(next: ActivatedRouteSnapshot,state: RouterStateSnapshot)
    : Observable | Promise | boolean {
    return this.myProjectService.getProject(projectNameFoundElsewhere).pipe(
      map((project) => {
        if (project) {
          next.data = project;
        }
        return !!project;
      }),
    );
    

    }`

    Then in your component

    constructor(private route: ActivatedRoute) {
        this.route.data.subscribe((value) => (this.project = value));
    }
    

    This way is a bit different than passing via a service since service keep the value in a behaviorSubject as long as it is not unset. Passing via tha guard make the data available for the current route. I havent check if the children routes keep the data or not.

提交回复
热议问题