如何在Angular2中的App类中访问RouteParams

时间:2016-04-13 13:34:10

标签: typescript angular angular-cli

我有一个使用CLI创建的Angular2应用程序,我需要以不同的模式运行。这些模式需要在查询字符串上传递,因为页面将托管在IFrame中。

根据我的阅读,我在顶层应用程序中访问RouteParams时出现问题,因为它们仅在路由组件中可用。

目前我通过访问javascript location.search对象实现了我想要的目标,但如果可能的话,我更愿意以正确的依赖注入方式执行此操作,以便我可以正确测试。

有人可以告诉我访问参数的正确方法。

@Component({
  selector: 'eox-app',
  providers: [ROUTER_PROVIDERS, RouteParams,
        FilterService,
        LoggingService,
        SpinnerService,
        StateService,
    ],
  templateUrl: 'app/eox.html',
  styleUrls: ['app//eox.css'],
  directives: [ROUTER_DIRECTIVES],
  pipes: []
})
@RouteConfig([

].concat(CliRouteConfig))

export class EoxApp {
    public menuItems = [
        { caption: 'Dashboard', link: ['DashboardRoot'] },
        { caption: 'Fonds', link: ['FundRoot'] },
        { caption: 'Logs', link: ['LogRoot'] },
        { caption: 'API', link: ['ApiRoot'] }
    ];

    public isEmbeded = false;
    constructor(
        private _router: Router,
        private _log: LoggingService,
        private _state: StateService,
        private _routeParams: RouteParams) {

        this.checkForEmbeded();
        let jwt = this.getCookie("eox-token");
        this._state.isAuthenticated = jwt === "123456";

        if(!this._state.isAuthenticated){
            this._log.log("Not authenticated", "Eox vNext");
            this._router.navigate(['DashboardRoot']);
        }
        else {
            this._log.log("Authenticated user", "Eox vNext");
        }
        if(this.isEmbeded && this._state.isAuthenticated)
         {
             this._log.log("Redirect to fundroot", "Eox vNext");
                this._router.navigate(['FundRoot']);
         }
    }

    getCookie(c_name) {
        var i, x, y, ARRcookies = document.cookie.split(';');
        for (i = 0; i < ARRcookies.length; i++) {
            x = ARRcookies[i].substr(0, ARRcookies[i].indexOf('='));
            y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
            x = x.replace(/^\s+|\s+$/g, "");
            if (x == c_name) {
                return unescape(y);
            }
        }
    }

    checkForEmbeded() {
        this.isEmbeded = location.search.indexOf("embeded") > 0;
        this._log.log("Embeded mode " + this.isEmbeded, "Eox vNext");
    }
}

1 个答案:

答案 0 :(得分:0)

您可以注入Router(就像您已经做过的那样),订阅它,然后访问下面所示的参数:

 constructor(
        private _router: Router,
        private _log: LoggingService,
        private _state: StateService,
        private _routeParams: RouteParams) {
    this._router.subscribe(path => {
      console.debug(this._router.currentInstruction.component.params);
    });
}