【问题标题】:How to share query param between parent and children routes?如何在父子路由之间共享查询参数?
【发布时间】:2019-03-13 19:05:10
【问题描述】:

我建立了一个网站,其中模板已被划分为组件。模板的页眉和页脚在 ma​​in.component.html 文件中,主体注入 router-outlet

导航中唯一改变的部分是正文。页眉和页脚保持不变。共享 storeid 查询参数以动态构建正文。

我遇到的问题是我必须从 ma​​in.component.ts 文件中获取 storeid 查询参数。我不知道如何使用我当前的路线配置来做到这一点。

以下是路线配置:

const routes: Routes = [
  {
    path: '',
    component: HomeLayoutComponent, // HOME PAGE
    children: [
      { path: 'home', component: HomeComponent },
      { path: '', redirectTo: '/home', pathMatch: 'full' },
    ]
  },
    {
    path: '', // I TRIED ':storeid' here but negative
    component: MainLayoutComponent, // MAIN LAYOUT IS DIVIDED AS DESCRIBED IN QUESTION. THIS IS THE STOREID I HAVE TO FETCH FROM HERE
    children: [
      { path: 'event-details/:storeid', component: EventDetailsComponent }, // SO AS HERE TOO.
      { path: '', redirectTo: '/home', pathMatch: 'full' },
    ]
  },
  { path: 'error-404', component: Error404PageComponent },
  { path: 'error-500', component: Error500PageComponent },
  { path: '**', component: HomeComponent }
];

谢谢

【问题讨论】:

    标签: angular router


    【解决方案1】:

    大卫可能有点晚了,但我想我有办法解决你的问题。

    通常,当使用在你的路由中传递的参数时,我们通过注入ActivatedRoute 来访问这些参数,然后订阅暴露的params observable 或通过将参数直接从当前 url 中获取使用snapshot.params

    export class {Your}Component implements OnInit {
    
      params
      constructor(private route: ActivatedRoute, ) { }
    
      ngOnInit() {
        this.route.params
          .pipe(first())
          .subscribe(x => {
            this.params = x
          });
         
        this.params =  this.route.snapshot.params
      }
    }

    这里棘手的部分(也就是你要问的问题)是,通过这种类型的访问,我们只能获取当前路由段中传递的参数。

    最简单的解决方案是使用不同的ParamsInheritanceStrategy。通过将继承策略设置为always,您将能够在附加到子段的组件中访问属于父路由段的参数。使用此策略时的棘手部分是,如果您有两个具有相同名称的参数,它们将覆盖,例如,如果您的路由是 store/:storeId/route/:storeId/child,第二个 :storeId 将覆盖前一个,如果它是从相关组件调用的第二个:storeId 的右侧分段(first => second 从左到右)。

    您可以在StackBlitz查看一个工作示例

    【讨论】:

      【解决方案2】:

      如果你想将数据从父组件传递给子组件,那么你需要用到两个东西:@Input 和属性绑定。

      如果要将数据从子组件传回父组件,可以使用@Output & EventEmitter 事件绑定

      请参考下面的网址,因为我已经回答了一个相关问题。 Angular 6 Communicating between Parent&Child components using @Output

      希望这有助于以正确的方式解决您的问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-28
        • 2022-01-12
        • 2020-08-27
        • 1970-01-01
        • 2011-10-26
        • 2020-08-11
        • 1970-01-01
        • 2017-10-03
        相关资源
        最近更新 更多