【问题标题】:angular 2 routing url issueangular 2路由url问题
【发布时间】:2017-08-24 13:12:40
【问题描述】:

这是我的 app.module.ts 文件。

 imports: [
        UniversalModule, // Must be first import. This automatically imports BrowserModule, HttpModule, and JsonpModule too.
        RouterModule.forRoot([
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'subscriber', component: SubscriberComponent },
            { path: '**', redirectTo: 'home' }
        ]),
        //HttpModule
        FormsModule
    ]

在我的订阅者组件中,我从 ngOnInit 中的 url 获取参数

ngOnInit() {

    let id = '';
    this.activatedRoute.params.subscribe((params: Params) => {
        id = params['id'];
        if (id != '') {
            this.viewData(id);
        }
        console.log(id);
    });
} 

效果很好,但每次我使用 url 来获取 param(xxx) 例如http://localhost:60009/xxx 我收到一个错误,因为路由重定向到这个 url,显然我没有任何链接。知道如何从路由中跳过重定向吗?

【问题讨论】:

    标签: angular redirect routing url-parameters


    【解决方案1】:

    如果您使用路由参数,则需要在路由配置中指定它们。您正在尝试读取参数id,但配置中的路由中未指定id。尝试将其添加到您的配置中:

    { path: ':id', redirectTo: 'home', pathMatch: 'full' },
    

    编辑

    Angular 既有路由参数也有查询参数。路由参数在路由配置中指定,如下所示:

    { path: ':id', redirectTo: 'home', pathMatch: 'full' },
    

    您可以通过以下方式访问组件中的那些:

    this.route.params.subscribe(data => data['id']);
    

    那么你也有查询参数。这些未在路由配置中指定。它们在 url 中看起来像这样:?id=something 你可以在你的组件中访问它们:

    this.route.queryParams.subscribe(queryParams =>  queryParams['id']);
    

    主要区别在于您是否在激活的路由上使用paramsqueryParams,以及是否在路由配置中指定了参数。

    【讨论】:

    • 如果我这样定义它,我如何从 url 中获取它?类似'localhost:60009/id=xxx'?
    • 您可以像现在一样从 url 获取它。如果是localhost:60009/id=xxx,那么它将是一个查询参数,而不是一个路由参数。
    • 可以给我一个查询参数的例子吗?
    猜你喜欢
    • 1970-01-01
    • 2017-02-10
    • 1970-01-01
    • 1970-01-01
    • 2017-07-23
    • 2016-12-19
    • 2016-09-23
    • 1970-01-01
    • 2016-06-11
    相关资源
    最近更新 更多