[英]How to Access RouteParams in the App class in Angular2
我有一個使用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");
}
}
你可以注入Router
(就像你已經做的那樣),訂閱它然后訪問params,如下所示:
constructor(
private _router: Router,
private _log: LoggingService,
private _state: StateService,
private _routeParams: RouteParams) {
this._router.subscribe(path => {
console.debug(this._router.currentInstruction.component.params);
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.