我是不是错过了什么?FormData和.get来自FormGroup



我有一些问题,我真的不知道代码中的问题在哪里。我已经搜索了一些,但没有找到。

我一直在尝试使用Angular Reactive Forms和HttpClient来制作一个联系表单,以进行发布请求等。有人对此有意见吗?问题位于FormData.append部分。我得到的错误消息是";对象可能为"null"对于我使用的三个表单Data.附件。

组件:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { MessageService } from 'primeng/api';
@Component({
selector: 'app-contact',
templateUrl: './contact.component.html',
styleUrls: ['./contact.component.scss']
})
export class ContactComponent implements OnInit {
contactForm: FormGroup;
submitted = false;
isLoading = false;
name: FormControl = new FormControl('', [Validators.required]);
email: FormControl = new FormControl('', [Validators.required, Validators.email]);
message: FormControl = new FormControl('', [Validators.required, Validators.maxLength(256)]);
honeypot: FormControl = new FormControl('');
constructor(private fb: FormBuilder, private messageService: MessageService, private http: HttpClient) {
this.contactForm = this.fb.group({
name: this.name,
email: this.email,
message: this.message,
honeypot: this.honeypot
});
}
ngOnInit(): void {
}
onSubmit() {
if (this.contactForm.status == 'VALID' && this.honeypot.value == '') {
this.contactForm.disable();
const formData:FormData = new FormData();
formData.append('name', this.contactForm.get('name').value);
formData.append('email', this.contactForm.get('email').value);
formData.append('message', this.contactForm.get('message').value);
this.isLoading = true;
this.submitted = false;
this.http.post('URL FROM GOOGLE HERE', formData).subscribe(
(response) => {
if (response == 'success') {
this.messageService.add({
severity: 'success',
summary: 'Success',
detail: 'Den mail er blevet sendt.'
});
} else {
this.messageService.add({
severity: 'error',
summary: 'Error',
detail: 'Afsendelsen af din mail fik en fejl.'
});
}
this.contactForm.enable();
this.submitted = true;
this.isLoading = false;
console.log(response);
},
(error) => {
this.messageService.add({
severity: 'error',
summary: 'Error',
detail: 'En fejl er opstået, prøv og genindlæs siden igen eller prøv senere.'
});
this.contactForm.enable();
this.submitted = true;
this.isLoading = false;
console.log(error);
}
);
}
}
}

组件的HTML

<section id="contact">
<div class="main">
<div class="text"> <!-- tittle og under tekst -->
<h1>Kontakt os</h1>
<p> Har du bruge for noget hjælp? <br>
Er der nogen fejl, som du kan se eller <br>
ville du bare i kontakt med os? <br>
Skriv endelig til os.
</p>
</div>
<form [formGroup]="contactForm" method="POST" (ngSubmit)="onSubmit(contactForm.value)">
<div class="input_warp">
<span class="p-float-label">
<input type="text" pInputText formControlName="name">
<label for="name">Navn</label>
<p-message severity="error" text="Du skal skrive dit navn ind."
*ngIf="!contactForm.controls['name'].valid && contactForm.controls['name'].dirty"></p-message>
</span>
</div>
<div class="input_warp"> <!-- skriv din email -->
<span class="p-float-label">
<input type="email" class="p-inputtext" pInputText formControlName="email">
<label for="email">Email</label>
</span>
<p-message severity="error" text="Du skal skrive din mail ind."
*ngIf="!contactForm.controls['email'].valid && contactForm.controls['email'].dirty"></p-message>
</div>
<input>
<div class="input_warp">
<textarea rows="10" cols="30" class="textarea-resize" pInputTextarea name="message"
placeholder="Besked her..."></textarea>
</div>
<div> <!-- send besked -->
<button class="button">Send besked</button>
</div>
</form>
</div>
</section>

应用程序模块

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { WelcomeComponent } from './before-login/welcome/welcome.component';
import { AboutComponent } from './before-login/welcome/components/about/about.component';
import { ContactComponent } from './before-login/welcome/components/contact/contact.component';
import { NavComponent } from './before-login/welcome/components/nav/nav.component';
import { SigninComponent } from './before-login/welcome/components/signin/signin.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { InputTextModule } from 'primeng/inputtext';
import { TooltipModule } from 'primeng/tooltip';
import { InputTextareaModule } from 'primeng/inputtextarea';
import { FormsModule } from '@angular/forms';
import { AngularFireModule } from '@angular/fire';
import { AngularFireAuthModule } from '@angular/fire/auth';
import { AngularFirestoreModule } from '@angular/fire/firestore';
import { environment } from '../environments/environment';
import { NgAuthService } from './auth/auth.service';
import { PasswordModule } from 'primeng/password';
import { ToastModule } from 'primeng/toast';
import { ForgotPasswordComponent } from './before-login/forgot-password/forgot-password.component';
import { EmailVerificationComponent } from './before-login/email-verification/email-verification.component';
import { DashboardComponent } from './after-login/dashboard/dashboard.component';
import { SignupComponent } from './before-login/welcome/components/signup/signup.component';
import { LazyLoadImageModule } from 'ng-lazyload-image';
import { UserProfileComponent } from './after-login/user-profile/user-profile.component';
import { MessageModule } from 'primeng/message';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
declarations: [
AppComponent,
WelcomeComponent,
AboutComponent,
ContactComponent,
NavComponent,
SigninComponent,
ForgotPasswordComponent,
EmailVerificationComponent,
DashboardComponent,
SignupComponent,
UserProfileComponent
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
InputTextModule,
TooltipModule,
InputTextareaModule,
FormsModule,
AngularFireModule.initializeApp(environment.firebase),
AngularFireAuthModule,
AngularFirestoreModule,
PasswordModule,
ToastModule,
LazyLoadImageModule,
MessageModule,
HttpClientModule
],
providers: [NgAuthService],
bootstrap: [AppComponent]
})
export class AppModule {
}

我在其他地方的帮助下修复了它。似乎我第一次忘记导入反应式表单,因为我只导入了表单。

然后我遇到了一些关于formData.append的问题。我找到了一个更好的解决方案来解决我在那部分所做的编码,效果很好。我还遇到了一些问题,无法使用response["result"]。并用(response: any) =>找到了解决方案我不知道我是否在表单部分打错了什么,但在复制了StackBlitz中的内容后,它现在可以工作了。

StackBlitz,一切正常:https://stackblitz.com/edit/angular-ivy-2yiyr3?file=src/app/contact/contact.component.ts

为什么使用"FormData"?你可以简单地发送一个简单的对象,例如

this.http.post('...',
{
name:this.contactForm.value.name,
email:this.contactForm.value.email,
message:this.contactForm.value.message,
}
)

最新更新