简体   繁体   English

如何在Angular应用程序根URL上配置route参数

[英]How to configure route parameter on Angular application root URL

Seems simple enough... my app.module looks like this: 似乎很简单...我的app.module看起来像这样:

 const appRoutes: Routes = [ { path: '', component: AppComponent }, { path: ':config', component: AppComponent } ]; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, RouterModule.forRoot(appRoutes) ], providers: [], bootstrap: [AppComponent] }) 

and the app.component code looks like this: 而app.component代码如下所示:

 constructor(private route: ActivatedRoute) { } config: string; ngOnInit() { this.config = this.route.snapshot.params['config']; } 

I want to be able to do something like hit http://localhost:4200/english and have the config property set to 'english'... but this.route.snapshot.params['config'] is undefined every time. 我希望能够执行类似http:// localhost:4200 / english的操作 ,并将config属性设置为“ english” ...但是每次都未定义this.route.snapshot.params ['config']。

Any help appreciated. 任何帮助表示赞赏。

There's actually nothin wrong of how you extract the params on your ngOnInit() but there's something wrong of how you missed to place your router-outlet (my assumption). 实际上,如何提取ngOnInit()上的参数并没有错,但是您错过了放置路由器出口的方式(我的假设)有问题。

AppComponent AppComponent

AppComponent is the root (router-outlet) that will handle all of your child routes. AppComponent是将处理所有子路由的根(路由出口)。

If you are fetching your route parameter and your AppComponent's Template is just a Plain HTML without the <router-outlet> then your this.route.snapshot.params['config']; 如果要获取route参数,而AppComponent的模板只是不带<router-outlet>this.route.snapshot.params['config']; HTML,则您的this.route.snapshot.params['config']; will become undefined 将变得不确定

@Component({
  selector: 'app-root',
  template: `I am AppComponent`        // Plain Template without <router-outlet>
})
export class AppComponent {...}

But if you will place the <router-outlet> on your AppComponent's Template, then your this.route.snapshot.params['config']; 但是,如果将<router-outlet>放在AppComponent的模板上,则您的this.route.snapshot.params['config']; will have a value, if the passed config parameter is '/english' then its snapshot param value is 'english' 将具有一个值,如果传递的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 
    }

}

Had created Stackblitz Demo for your reference in regards to your concern 创建了Stackblitz演示以供您参考

Demo Output 演示输出

演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM