2016-03-30 55 views
2

我想從一個URL中的查詢參數的成分在Angular2Angular2查詢參數從指數URL

版本:「angular2」:「故宮:[email protected]」,

我試圖提取組件中的id查詢參數並將其顯示出來

這是請求。

本地主機:8080/index.html的ID = 1個

boot.ts

import 'reflect-metadata'; 
import 'angular2/bundles/angular2-polyfills'; 
import { bootstrap } from 'angular2/platform/browser'; 
import { provide} from 'angular2/core'; 
import { AppComponent } from './app.component'; 
import {ROUTER_PROVIDERS, Location, LocationStrategy,  HashLocationStrategy} from "angular2/router"; 
import {HTTP_PROVIDERS} from "angular2/http"; 

bootstrap(AppComponent , [ROUTER_PROVIDERS, HTTP_PROVIDERS, provide(LocationStrategy, {useClass: HashLocationStrategy})]); 

這裏是app.component.ts

import { Component } from 'angular2/core'; 
import {Router, Location, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, RouteConfig, RouteParams} from 'angular2/router'; 

@Component({ 
    selector: 'my-app', 
    template: '{{welcome}} {{queryParam}}', 
    directives: [ROUTER_DIRECTIVES] 
}) 
export class AppComponent { 
    welcome: string = 'Query Param test!' 
    queryParam : string; 

    constructor(private _location: Location, private _routeParams:  RouteParams){ 
     console.log(_routeParams.get('id')); 
     this.queryParam = _routeParams.get('id'); 
    } 

} 

我不斷收到此錯誤:

error message

我從另一篇文章中得到了這個解決方案。不知道如何修正這個錯誤

一個

+0

我可以知道你的'RouteConfig'代碼在哪裏嗎? –

回答

0

RouteParams它不是在根組件可用。它僅適用於可路由組件。

RouterOutlet索裏的代碼,在其activate功能,你可以看到下面的

var providers = Injector.resolve([ 
    provide(RouteData, {useValue: nextInstruction.routeData}), 
    provide(RouteParams, {useValue: new RouteParams(nextInstruction.params)}), 
    provide(routerMod.Router, {useValue: childRouter}) 
]); 

基本上RouteParams正在通過RouterOutlet注入到路由組件,您將無法訪問在非路由組件(抱歉重複自己)。

0

您可以從AppComponent中的_location.path()獲取查詢參數。你必須自己解析它們。我正在尋找同樣的東西,並沒有找到更好的解決方案。

我希望有人跟進這個。