Angular 2新手求助:如何将表单数据提交至服务器API?
Hey there! Let's work through your form submission issue step by step—you've got this, and we'll get it sorted out.
First, let's fix your current single-field submission problem
Looking at your code, there are a few small but critical issues that are stopping your test submission from working:
- Undefined variable mistake: You defined
userNames: any[]but tried to push tothis.user(which doesn't exist) in youruserNamemethod. It should bethis.userNames.push(user)instead. - Missing request headers: Most APIs require a
Content-Type: application/jsonheader to properly parse the JSON payload you're sending. Your current code doesn't set this, which might be causing the server to reject the request. - Incorrect variable types: You declared
name: any[],password: any[], etc.—these should be single strings (not arrays) since they're storing individual input values. - Non-standard submission trigger: Using
(keyup.enter)on just the first name input isn't how forms are typically handled. Let's shift to using the form's native submit event for better usability.
Here's the fixed version of your component code for single-field testing:
import { Component, OnInit, ViewEncapsulation } from '@angular/core'; import { Http, Headers, RequestOptions } from '@angular/http'; @Component({ selector: 'app-add-account', templateUrl: './add-account.component.html', styleUrls: ['./add-account.component.css'], encapsulation: ViewEncapsulation.None }) export class AddAccountComponent implements OnInit { name: string; // Changed from array to single string userNames: any[] = []; // Initialize empty array private url = 'your-company-api-url'; constructor(private http: Http) { } ngOnInit(): void { } userName(input: HTMLInputElement) { const user = {name: input.value}; input.value = ''; // Set up required headers const headers = new Headers({ 'Content-Type': 'application/json' }); const options = new RequestOptions({ headers: headers }); this.http.post(this.url, JSON.stringify(user), options) .subscribe(response => { user['id'] = response.json().id; this.userNames.push(user); // Fixed variable name here console.log('Submission successful:', response.json()); }, error => { console.error('Submission failed:', error); // Add error handling! }); } }
Now, let's tackle submitting multiple form fields (the real goal!)
For a registration form, using Angular's Template-Driven Forms is perfect for beginners—it's straightforward and requires minimal boilerplate. Here's a complete working example:
Step 1: Update your template
Add ngModel directives to each input (to bind values to your component) and use the form's ngSubmit event to handle submission:
<form #registerForm="ngForm" (ngSubmit)="onSubmit(registerForm.value)"> <div class="row col-md-12"> <input name="firstName" ngModel type="text" class="rounded-inputs25 col-md-3 first-name-input add-account-inputs" placeholder="First name" required > <input name="lastName" ngModel type="text" class="rounded-inputs25 col-md-3 last-name-input add-account-inputs" placeholder="Last name" required > </div> <input name="email" ngModel type="email" class="rounded-inputs25 col-md-6 add-account-inputs" placeholder="Email" required > <input name="password" ngModel type="password" class="rounded-inputs25 col-md-6 add-account-inputs" id="password" placeholder="Password" required > <input name="confirmPassword" ngModel type="password" class="rounded-inputs25 col-md-6 add-account-inputs" id="confirm_password" placeholder="Confirm password" required > <button type="submit" class="submit-btn">Create Account</button> </form>
Step 2: Update your component
Add a submission method that handles all form data, includes validation (like password matching), and sends the full payload to your API. Also, we'll switch to HttpClient (the modern replacement for Http that handles JSON automatically):
import { Component, OnInit, ViewEncapsulation } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; @Component({ selector: 'app-add-account', templateUrl: './add-account.component.html', styleUrls: ['./add-account.component.css'], encapsulation: ViewEncapsulation.None }) export class AddAccountComponent implements OnInit { registeredUsers: any[] = []; private url = 'your-company-api-url'; constructor(private http: HttpClient) { } ngOnInit(): void { } onSubmit(formData: any) { // First, validate password match if (formData.password !== formData.confirmPassword) { alert('Passwords do not match! Please try again.'); return; } // Prepare payload (exclude confirmPassword since the server doesn't need it) const userPayload = { firstName: formData.firstName, lastName: formData.lastName, email: formData.email, password: formData.password }; // Set headers (HttpClient makes this simpler!) const headers = new HttpHeaders({ 'Content-Type': 'application/json' }); this.http.post(this.url, userPayload, { headers: headers }) .subscribe( (response: any) => { // Add the returned user ID to our local list const newUser = { ...userPayload, id: response.id }; this.registeredUsers.push(newUser); console.log('Account created successfully:', response); // Reset the form after successful submission registerForm.reset(); }, error => { console.error('Error creating account:', error); // Show user-friendly error message here } ); } }
Step 3: Don't forget to import required modules!
In your AppModule (or the module where your AddAccountComponent is declared), add these imports to make the form work:
import { FormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http'; @NgModule({ imports: [ // ... other imports FormsModule, // Required for template-driven forms HttpClientModule // Required for HttpClient ], // ... other module settings }) export class AppModule { }
Quick notes to remember:
- Always handle errors in your subscriptions—this will help you debug why submissions fail (like network issues or API validation errors).
- Using
HttpClientinstead of the oldHttpmodule saves you from manually stringifying JSON and parsing responses. - Template-driven forms use
ngModeland form references (#registerForm) to easily access form values.
If you're still having trouble, check your browser's dev tools Network tab to see exactly what request is being sent—this is the best way to debug API submission issues!
内容的提问来源于stack exchange,提问作者Mohamed Wahshey

