Angular2问题检索URL参数

时间:2018-01-23 16:08:50

标签: angular typescript query-parameters

我目前正在我的angular 2应用程序(.net core 2后端)中实现确认电子邮件过程。目前的工作流程是:用户注册 - >他们会收到一封电子邮件以确认他们的帐户 - >他们点击链接 - >它们被定向到一个角度组件,该组件应该读取userId并生成令牌。浏览器中的网址为http://localhost:35000/confirm-email?token=CfDJ8OR7TVlXC69LsUgYal539cq4%2FcxvIXYoyaXcvLXQofMfK8d%2Bp6JE02IBATC49meM8bNSq9pgzq%2B7MspZLt7h1hfetLF2iVkXRkQZHFiJluhRpJbZ7kkafpyrbXjs82KFjkzVSOEDGV4sC6x4%2Bd0i0SXejfK%2F%2FpZgKTnOhdvB%2FwbLK5iauwdDXnjV7ZN7LHA0HInpvBPF2OOpdjJ%2FXicRLYLq5ic4Pz7SnXz0iwOTj4HJQIZAX%2FA1DqgvrPR6vuaOwQ%3D%3D&userId=5da26d4c-f737-481c-9142-affd89e8e9d6

将我转到下面的确认电子邮件组件但是我无法正确阅读我的参数tokenuserId - 它们始终未定义。我的角度组件的简化代码如下:

export class ConfirmEmailComponent implements OnInit {
    emailConfirmed: boolean = false;

    constructor(private userService: UserService,
        private router: Router,
        private activatedRoute: ActivatedRoute) { }

    ngOnInit() {
        this.activatedRoute.params.subscribe((params: Params) => {
          let token = params['token'];
          let userId = params['userId'];

          this.userService.confirmEmail(token, userId).subscribe(
            (data) => {
              this.emailConfirmed = true;
            });
        });
    }
}

1 个答案:

答案 0 :(得分:4)

你需要订阅activatedRoute.queryParams,而不是params,因为你通过查询参数传递数据,而不是预定义的参数('my-url?key = value'而不是'my-url) /:someParam')。就像这样:

this.activatedRoute.queryParams.subscribe((params: Params) => { //etc