javascript API POST请求未从Angular前端应用程序发送到后端

7rfyedvj  于 2023-04-10  发布在  Java
关注(0)|答案(2)|浏览(134)

我在Angular中创建了一个用户注册页面前端,它似乎有正确的代码来调用POST register方法,并将数据发送到后端进行用户注册,但没有请求被调用到后端,也没有发送用户详细信息,console.log没有显示调用register()方法的内容,浏览器开发工具中的网络选项卡也有点空。
共享相关文件的代码:
register.component.html

<div class="registrationForm" type="FormGroup">
<form (ngSubmit)="onSubmit()">

<div class="form-row">

  <div class="form-group">
    <label for="exampleInputUsername">First Name</label>
    <input type="text" [(ngModel)]="fname"  class="form-control" id="exampleInputUsername" placeholder="eg. John" [ngModelOptions]="{standalone: true}">
  </div>

  <div class="form-group">
    <label for="exampleInputUsername">Last Name</label>
    <input type="text" [(ngModel)]="lname"  class="form-control" id="exampleInputUsername" placeholder="eg. Doe" [ngModelOptions]="{standalone: true}">
  </div>

</div>

<div class="form-row">

  <div class="form-group">
    <label for="exampleInputEmail1">Email:</label>
    <input type="email" [(ngModel)]="email" name="mail" class="form-control" placeholder="eg. john@gmail.com" required >
  </div>
  <!--
  <div class="form-group">
    <label for="exampleInputEmail1">Email:</label>
    <input type="email" name="email" required class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="eg. john@gmail.com">
  </div>
  -->

  <div class="form-group">
    <label>Password:</label>
    <input type="password" [(ngModel)]="password" name="password" class="form-control" required>
  </div>

</div>

<button type="submit" class="btn btn-primary" style="margin-left:220px;margin-top:20px;">Submit</button>

register.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { UserService } from 'src/app/register/userservice'; //import the user service
import { FormBuilder, FormGroup, Validators } from '@angular/forms'; //import form modules
import { catchError, tap } from 'rxjs';


@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.less']
})
export class RegisterComponent implements OnInit {

  registrationForm: FormGroup;
  email:string ='';
  password:string ='';
  fname:string ='';
  lname:string ='';
  submitted = false;

  constructor(
    private formBuilder: FormBuilder,
    private router: Router,
    private UserService: UserService,
  )
 {
  this.registrationForm = this.formBuilder.group({});
  }

  ngOnInit() {
    this.registrationForm = this.formBuilder.group({
      email: [this.email, [Validators.required, Validators.email]],
      password: [this.password, [Validators.required, Validators.minLength(6)]],
      fname: [this.fname],
      lname: [this.lname],
    });
  }

  // convenience getter for easy access to form fields
  get f() { return this.registrationForm.controls; }

  onSubmit() {
    console.log('Submit button clicked');
    this.submitted = true;
    if (this.registrationForm.invalid) {
      return;
    }
this.UserService.register(
    this.registrationForm.controls['email'].value, 
    this.registrationForm.controls['password'].value, 
    this.registrationForm.controls['fname'].value, 
    this.registrationForm.controls['lname'].value)
    .pipe(
      tap((response: any) => console.log('Response from server:', response)),
      catchError((error: any) => {
        console.log('Error from server:', error);
        return throwError(error);
      })
    )
    .subscribe();
    
  }

  }

function throwError(error: any): any {
  throw new Error('Function not implemented.');
}

userservice.ts

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

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

  private baseUrl = 'http://localhost:8080/'; // replace with your backend URL //backend url for post mapping of user details

  constructor(private http: HttpClient) { }

  //check the use of 'Observable'
  register(email: string, password: string, fname: string,lname: string): Observable<any> {
    const data = {
      email: email,
      password: password,
      fname: fname,
      lname: lname
    };
    console.log('User service register method called with user:', data);
    return this.http.post(`${this.baseUrl}/api/register`, data);
  }
}

我的浏览器控制台注册提交按钮被点击,但没有关于任何方法,请帮助。

x4shl7ld

x4shl7ld1#

您的registrationForm.invalid总是返回true,因为您在表单上设置了一些验证器,但您将模板元素绑定到本地变量(this.email等),而不是FormControl的。
你可以用这些变量初始化你的表单,但是它们只被用作默认值。通过模板改变它们并不会更新表单。

this.registrationForm = this.formBuilder.group({
      email: [this.email, [Validators.required, Validators.email]],
      password: [this.password, [Validators.required, Validators.minLength(6)]],
      fname: [this.fname],
      lname: [this.lname],
    });

一种解决方案是将模板元素绑定到FormControl,而不是本地变量。

gstyhher

gstyhher2#

您在user.service中定义了具有可观察输出的register函数,但是在该函数中没有返回任何可观察输出

public register(email: string, password: string, fname: string,lname: string): Observable<any> {
  const data = {
    email: email,
    password: password,
    fname: fname,
    lname: lname
  };
  return new Observable(observer=>{
    this.http.post(`${this.baseUrl}/api/register`, data);
  })
}

相关问题