从 Angular 5 中的 URL 获取数据

Zee*_*lik 2 routing angular-routing angular

我在网址栏中输入了一个链接。

http://localhost:4200/reset-password-action/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9/5
Run Code Online (Sandbox Code Playgroud)

我想从 url获取eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ95

我在app-routing.module.ts文件中有它。

const routes: Routes = [
  { path: 'reset-password-action/:token/:user_id', component: NewPasswordComponent }
];
Run Code Online (Sandbox Code Playgroud)

我需要一个简单的语法来获取这些数据。

Abh*_*hek 5

首先你想从哪里得到这些数据? 如果你想在同一个组件中,在你的情况下,我认为它是 NewPasswordComponent

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

@Component({...})
export class NewPasswordComponent implements OnInit {
  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    console.log(this.route.snapshot.params.token);
    console.log(this.route.snapshot.params.user_id);
  } 
}
Run Code Online (Sandbox Code Playgroud)

或者你也可以像下面这样:

 constructor(private route: ActivatedRoute) {}

    ngOnInit() {
      this.route.params.subscribe(event => {
      this.token = event.token;
      this.user_id = event.user_id;
     });
    }
Run Code Online (Sandbox Code Playgroud)