【问题标题】:Can't send data to backend无法将数据发送到后端
【发布时间】:2019-11-20 06:35:48
【问题描述】:

我想简单地将数据发送到后端以注册用户。

register.component.ts

import { Component, OnInit } from '@angular/core';
import {FormBuilder, Validators} from '@angular/forms';
import {RegisterService} from './register.service';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.sass']
})
export class RegisterComponent implements OnInit {
  registerFormGroup = this.fb.group({
    email: ['', Validators.email],
    password: ['', Validators.pattern('^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$')]
  });

  constructor(private fb: FormBuilder, private registerService: RegisterService) { }

  ngOnInit() {
    this.registerFormGroup.valueChanges.subscribe(inputFields => {
      console.log(this.registerFormGroup.value);
    });
  }

  // Submit the form
  private _onSubmit() {
    // There are some errors
    if (this.registerFormGroup.status === 'INVALID') {
      this.registerFormGroup.markAllAsTouched();
    } else {
      console.log('Ready to send'); // That works!
      // NO errors. Let's register the user
      this.registerService.register(this.registerFormGroup.value);
    }
  }

}

register.service.ts

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class RegisterService {

  constructor(private http: HttpClient) { }

  /**
   * @description Register the user
   * @param data JSON that includes E-Mail and password
   */
  public register(data) {
    return this.http.post('/register', data);
  }
}

使用this.registerService.register(this.registerFormGroup.value); 我尝试将数据发送到后端,但由于某种原因我的服务器没有收到请求。我做错了什么?

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    你可能应该subscribe

    this.registerService.register(this.registerFormGroup.value)
        .subscribe(response => {
          ...
        });
    

    【讨论】:

    • 是的,解决了它。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-18
    • 1970-01-01
    相关资源
    最近更新 更多