![](/img/trans.png)
[英]How to configure route on the basis of url parameters from different application.
[英]How to configure route parameter on Angular application root URL
似乎很簡單...我的app.module看起來像這樣:
const appRoutes: Routes = [ { path: '', component: AppComponent }, { path: ':config', component: AppComponent } ]; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, RouterModule.forRoot(appRoutes) ], providers: [], bootstrap: [AppComponent] })
而app.component代碼如下所示:
constructor(private route: ActivatedRoute) { } config: string; ngOnInit() { this.config = this.route.snapshot.params['config']; }
我希望能夠執行類似http:// localhost:4200 / english的操作 ,並將config屬性設置為“ english” ...但是每次都未定義this.route.snapshot.params ['config']。
任何幫助表示贊賞。
實際上,如何提取ngOnInit()上的參數並沒有錯,但是您錯過了放置路由器出口的方式(我的假設)有問題。
AppComponent
AppComponent是將處理所有子路由的根(路由出口)。
如果要獲取route參數,而AppComponent的模板只是不帶
<router-outlet>
的this.route.snapshot.params['config'];
HTML,則您的this.route.snapshot.params['config'];
將變得不確定
@Component({
selector: 'app-root',
template: `I am AppComponent` // Plain Template without <router-outlet>
})
export class AppComponent {...}
但是,如果將
<router-outlet>
放在AppComponent的模板上,則您的this.route.snapshot.params['config'];
將具有一個值,如果傳遞的config參數為“ / english”,則其快照參數值為“ english”
@Component({
selector: 'app-root',
template: `
<h1>{{ config }}</h1>
<router-outlet></router-outlet> // Add router-outlet
`
})
export class AppComponent implements OnInit {
config: string;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.config = this.route.snapshot.params['config']; // 'english' if the url has a supplied param of /english
}
}
創建了Stackblitz演示以供您參考
演示輸出
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.