您可以將RouteParams
對象注入到構造函數中,然後調用get
函數。這是official documentation
import {bootstrap, Component} from 'angular2/angular2';
import {Router, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, RouteConfig} from 'angular2/router';
@Component({directives: [ROUTER_DIRECTIVES]})
@RouteConfig([
{path: '/user/:id', component: UserCmp, as: 'UserCmp'},
])
class AppCmp {}
@Component({ template: 'user: {{id}}' })
class UserCmp {
id: string;
constructor(params: RouteParams) {
this.id = params.get('id');
}
}
關於三個語法的例子,他們似乎言自明
{ path: '/:myParam', component: MyComponent, as: 'MyCmp' }, //Route with param
{ path: '/staticPath', component: ..., as: ...}, // Fixed route
{ path: '/*wildCardParam', component: ..., as: ...} //match any route which ends with wildCardParam
更新: http://plnkr.co/edit/iRUP8B5OUbxCWQ3AcIDm?p=preview
它使用RouteParams
從文檔見本plunkr 我觀察到的一件事是RouteParams只有在路由本身有參數時纔可用定義,否則你會得到下面的錯誤。
我已經使用你的代碼,但得到錯誤命名爲「RouteParams」沒有找到。我應該不得不從某處導入或注入RouteParams? –
@Pardeepjain看到我的更新 – Chandermani
thnx for plnkr。但是我用'@ injectable'和'@ inject'完成了我的問題 –