【问题标题】:Angular 9: passing param from url together a form paramsAngular 9:将来自 url 的参数一起传递给表单参数
【发布时间】:2025-11-25 21:00:01
【问题描述】:

我需要将一个 url 参数传递给后端一起形成参数。我从这样的 URL 获取令牌参数:

private initForm(): void {
    this.route.queryParams.subscribe(params => {
      const token = params['token']; // get the token from url
      console.log(token)
    });

    this.formGroup = this.formBuilder.group({
      password: ['', Validators.required],
      password_confirmation: ['', Validators.required],
      reminder: ['', Validators.required]
    });
  }

在我的onSubmit 方法上,我有它:

public onSubmit(event: any): void {

    if (this.formGroup.invalid) {
      return this.formGroup.markAllAsTouched();
    }

    const { password, password_confirmation, reminder } = this.formGroup.value;

    const subscription = this.updatePasswordComponentService
      .updatePassword(password, password_confirmation, reminder)
      .subscribe(result => {
        console.log(result);
        subscription.unsubscribe();
      });
  }

updatePassword 方法

public updatePassword(password: string, password_confirmation: string, reminder: string): Observable<any> {
    return this.httpClient.post(url, {
      password, password_confirmation, reminder
    });
  }

我需要像这样传递参数:

public updatePassword(password: string, password_confirmation: string, reminder: string, token: string): Observable<any> {
    return this.httpClient.post(url, {
      password, password_confirmation, reminder, token
    });
  }

如何将token 包含在passwordpassword_confirmationreminder 参数中?

【问题讨论】:

  • 这里缺少 main 方法,请同时包含您服务中的 updatePassword 方法。
  • .updatePassword(password, password_confirmation, prompt, this.token) ...?
  • 不行,这样不行!

标签: angular


【解决方案1】:

你总是可以像这样从路由快照中获取 queryParams

this.updatePasswordComponentService.updatePassword(
    password, 
    password_confirmation, 
    reminder, 
    this.route.snapshot.queryParams.token)

并将其作为请求正文传递

【讨论】: