【问题标题】:Angular 2: Get query params when app bootstrapping (before redirect)Angular 2:在应用程序引导时获取查询参数(重定向之前)
【发布时间】:2017-11-05 10:01:00
【问题描述】:

目前,我正在实施一个嵌入聊天系统,该系统允许用户将客户端聊天应用程序嵌入到他们的网站中。使用 Angular 2(版本 4)的客户端聊天应用程序。有两种类型的用户,代理和客户端。将使用他们的凭证和网站 ID(在代理注册其网站时创建)来识别客户。因此,我需要将网站 ID 传递到客户端应用程序的每个请求中。我计划将此网站 ID 作为查询参数放入 url。但是,当应用程序引导时我无法获得此值。

网址如下所示:

http://localhost:3000?site=123456

这里是应用路由,初始化时会根据登录状态重定向根路径:

const routes: Routes = [
    {
        path: '',
        redirectTo: '/chat',
        pathMatch: 'full'
    }
];

在应用程序组件中,我尝试像这样捕获查询参数:

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import {
    ActivatedRoute, Router, RouterState,
    RouterStateSnapshot
} from "@angular/router";

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss'],
    encapsulation: ViewEncapsulation.None

})
export class AppComponent implements OnInit {
    title = 'app works!';

    constructor(private router: Router,
                private activatedRoute: ActivatedRoute) {
        //
    }

    ngOnInit() {
        this.activatedRoute.queryParams.subscribe(p => console.log(p)); // result empty

        console.log(this.router.routerState.snapshot.root.queryParams); // result empty
    }
}

假设用户已经登录,应用程序将重定向到 http://localhost:3000/chat 并且我尝试捕获的 queryParams 返回空(在 ngOnInit 方法中),url 中的查询参数也像 http://localhost:3000/chat 一样消失。如果我将查询参数放在 slug /chat 之后(例如http://localhost:3000/chat?site=123456),我可以捕获该值并且查询参数保留在 url 中。我怀疑重定向导致了这种情况,任何人都可以指出我哪里出错了。谢谢。

【问题讨论】:

    标签: angular typescript query-parameters


    【解决方案1】:

    您必须将路由器模块设置为使用哈希,它才能工作 在 app.module 中 替换路由器模块
    RouterModule.forRoot(routes, {useHash:true}),

    【讨论】:

      【解决方案2】:

      您可以在路由器更改之前使用 Guard 请求路由

      函数canActivate可以得到 激活路由:激活路由快照, 状态:RouterStateSnapshot 作为参数,查询参数的值位于 state.root.queryParams.site

      不要忘记从函数中返回真值

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-09
        • 2017-07-22
        • 2016-08-10
        • 2014-06-01
        • 2017-08-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多