有没有更好的方法来获取Angular2中的祖先路径参数? [英] Is there better way to get ancestor route params in Angular2?

查看:60
本文介绍了有没有更好的方法来获取Angular2中的祖先路径参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从不是父级甚至祖父母级的路由中获取参数,它只是到根路径的上方.我知道角度2中所示的方法:从父组件获取RouteParams 或通过共享服务,但我投入的情况(至少我认为是这样)使那些人不太适合这样做.所以这就是我得到的:

I need to get param from route which is not parent and not even grand-parent, it's simply somewhere above, along the path to root. I am aware of approaches like shown in Angular 2: getting RouteParams from parent component or through shared service but situation which I put myself into (at least I think so) makes those not well suited for it. So here is what I got:

我有延迟加载的子模块,需要从父上下文中获取id.这种情况在路由配置中或多或少看起来像这样:

I have lazily loaded sub-module which needs id from parent context. Situation more or less looks in routing configuration like this :

// Parent/outer module routing
const outerRoutes: Routes = [
    {
        path: 'container/:containerId',
        component: ContainerComponent,
        children: [
            { path: 'model', loadChildren: 'app/container/model/model.module#ModelModule' },
            { path: '', component: ContainerDetailsComponent }
        ]
    }
];

// Child/inner module routing
const innerRoutes: Routes = [
    {
        path: '',
        component: ModelComponent,
        children: [
            { path: ':id', component: ModelDetailsComponent },
            { path: '', component: ModelsComponent }
        ]
    }
];

ModelsComponent需要加载属于给定Container的所有Model实例.因此,我决定采用.parent的方法,但是在写完第二个.parent之后我的牙齿开始受伤,并且仍然有第三个出现:

ModelsComponent needs to load all Model instances belonging to given Container. So I decided to go through .parent approach but my teeth started to hurt after writing 2nd .parent and there was still 3rd to come:

this.route.parent.parent.parent.params
  .switchMap((params: Params) => this.modelService.getAllBelongingTo(params['containerId']))
  .subscribe(
    (models: Model[]) => this.models = models,
    error => this.raceEvent = null
  );

共享服务是某种方式的一种选择,但是由于子模块延迟加载的事实,我必须将其放在核心模块中,以使其具有相当的全局性(我不喜欢).

Shared service is somehow an option but due to the fact that child module is lazily loaded I would have to put it in core module making it quite global (which I don't like).

经过一番苦苦挣扎之后,我开始看下面的代码,该代码只是将所有ActivatedRoute放到根,合并它们,查找参数并使用它.我不喜欢它,因为我认为它太复杂,难以理解并且有几英里的臭味(或者说是血腥的),但是它可以工作,而且我不必担心嵌套是否更改.我只需要确保:containerId在root路径上的某个位置即可.

After a bit of struggling I came to following piece of code, which simply takes all ActivatedRoute up to the root, combines them, does lookup for param and consumes it. I don't like it as in my opinion it too complex , unreadable and stinks from a mile (or in other words is gory as heck) but works and I don't have to take care whether nesting changes. I simply have to make sure that :containerId is somewhere up there on the path to root.

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { Observable } from 'rxjs/Observable';

import { Model } from './model';
import { ModelService } from './model.service';

@Component({
    ...
})
export class ModelsComponent implements OnInit {
    models: Model[];

    constructor(
        private route: ActivatedRoute,
        private modelService: ModelService) { }

    ngOnInit() {
        const paramsArr = this.route.pathFromRoot.map(route => route.params);

        Observable.combineLatest(paramsArr)
            .switchMap(arrOfParams => {
                const params = arrOfParams.find(p => p['containerId'] !== undefined),
                      id = params && params['containerId'];
                return id ? this.modelService.getAllBelongingTo(id) : [];
            })
            .subscribe(
                (models: Model[]) => {
                    // yay! we got sth
                    this.models = models;
                },
                error => {
                    // handle big nono
                }
            );
    }
}

有没有更好的方法来处理所描绘的情况?

Is there a better way to handle depicted situation?

推荐答案

通常,我认为您的方法确实有意义.

Generally, I think your approach does make sense.

我不知道代码的确切背景,但是确实感觉像是一个子组件,想了解很多有关父实例数据的信息,我同意@Aravind的评论,这可能是在全局状态管理中最好解决的问题解决方案,例如redux或ngrx.话虽如此,如果这就是您所需要的,我知道您不想引入这种复杂性.

I do not know the exact background for the code, but it does feel like a child component wanting to know lots about parent instance data, and I would agree with @Aravind's comment that this is likely best dealt with in global state management solutions such as redux or ngrx. That being said, if this is all you would need it for, I understand you would not want to introduce that level of complexity.

我只会对您的rxchain进行些微调整,以使其更具可读性.

I would only make minor adjustments to your rxchain so it is more readable.

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { Observable } from 'rxjs/Observable';

import { Model } from './model';
import { ModelService } from './model.service';

@Component({
    ...
})
export class ModelsComponent implements OnInit {
    models: Model[];

    constructor(
        private route: ActivatedRoute,
        private modelService: ModelService) { }

    ngOnInit() {
        const paramsArr = this.route.pathFromRoot;

        Observable.from(paramsArr)
            .map(route => route.params)
            .filter(params => params.containerId)
            .switchMap(containerId => this.modelService.getAllBelongingTo(containerId))
            .subscribe(
                (models: Model[]) => {
                    // yay! we got sth
                    this.models = models;
                },
                error => {
                    // handle big nono
                }
            );
    }
}

但是请注意,此实现仅在有containerId作为父级的参数时设置this.models

Note however this implementation will only set this.models when there is a containerId as a parameter to a parent

修正错别字

这篇关于有没有更好的方法来获取Angular2中的祖先路径参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆