2

我想从 url 获取令牌,但它返回 null 作为值。

app.component.ts:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {    
  constructor(private route: ActivatedRoute) { }

    ngOnInit(){  
    const token = this.route.snapshot.paramMap.get('token');
    console.log(token);

和路由.ts

{ path: ':token', component: AppComponent }

我想在 / 之后抓取 url 中的内容,例如:localhost:4200/content-to-grab 有什么解决方案吗?

4

4 回答 4

2

你的方法没问题,还有另一个概念问题:

您正在尝试将路径关联到根组件

最有可能的是,您的根模块如下所示:

@NgModule({
  imports: [
    RouterModule.forRoot(...)
  ],
  declarations:[
    ...
    AppComponent,
    ...
  ],
  boostrap: [AppComponent]
})
export class AppModule {}

The first instance of AppComponent instantiated by the framework during the bootstraping step will be used as root component, and as a consequence, the injected ActivatedRoute will be sort of "disconected" from that route definition of yours.

Furthermore, instances of AppComponent resolved through the RouterOutlet directive will be aware of your route definition.

You can check this by yourself in the following stackblitz.

ActivatedRoute注入第一个实例的实例不会AppComponent以异步或同步方式反映路由参数。如果你导航到类似的东西{url}/#/bla,第二个实例AppComponent将因为<router-outlet>. ActivatedRoute注入其中的实例将反映路由参数值,两者都是同步的。并且是异步的。

于 2018-11-15T15:40:54.233 回答
0

试着像这样抓住它。

this.route.snapshot.params["token"]
于 2018-11-15T14:03:36.567 回答
-1

将您的代码更改为

this.route.paramMap.subscribe(params => { console.log(params.get('token'));})
于 2018-11-15T13:46:07.527 回答
-1
ngOnInit(){  
    const token = this.activatedRout.snapshot.params.token;
}
于 2018-11-15T14:15:36.900 回答