如何解决Nativescript使用表单创建新记录
我正在开发带有angular应用程序的Nativescript,在其中我创建了一个表单供用户使用表单添加新记录。该应用程序正在使用rest API在数据库上创建新记录。这是我遇到的错误
newContact(){
this.contactservices.submitContact(this.postContact).subscribe(
result => this.router.navigate(["/home"]),error => console.error(error)
)
}
headers = new HttpHeaders({
"Content-Type": "application/json",Authorization: "Token 5a72afc446dd4c38e5"
});
constructor(private http: HttpClient) { }
submitContact(opost: ContactData){
return this.http.post(this.url,opost,{headers: this.headers})
}
<StackLayout >
<TextField hint="Your First Name" [(ngModel)]="postContact.first_name" #element></TextField>
<TextField hint="Your Last Name" [(ngModel)]="postContact.last_name" #element></TextField>
<TextField hint="Your Email" [(ngModel)]="postContact.email" #element></TextField>
<TextView hint="Type your message here" [(ngModel)]="postContact.message" #element></TextView>
</StackLayout>
<FlexboxLayout class="about-button" alignItems="center">
<Button class="btnBack" text="Back"></Button>
<Button class="btnSend" text ="Send" (tap)="newContact()"></Button>
</FlexboxLayout>
解决方法
这是我的解决方法,希望这对以后的工作有所帮助
</StackLayout>
<StackLayout >
<TextField hint = "Your First Name" returnKeyType="next" required ngModel #fname ="ngModel"></TextField>
<label
*ngIf ="!fname.valid && fname.touched"
text ="Please enter a valid first name"></label>
<TextField hint="Your Last Name" required ngModel #lname ="ngModel"></TextField>
<label
*ngIf ="!lname.valid && lname.touched"
text ="Please enter a valid last name"></label>
<TextField hint="Your Email" keyboardType="email" required ngModel #email="ngModel"></TextField>
<label
*ngIf ="!email.valid && email.touched"
text ="Please enter a valid email address"></label>
<TextView hint="Type your message here" returnKeyType="done" required ngModel #message="ngModel"></TextView>
<label *ngIf ="!message.valid && message.touched"
text ="Please enter a valid message"></label>
</StackLayout>
<FlexboxLayout class="about-button" alignItems="center">
<Button class="btnBack" text="Back"></Button>
<Button class="btnSend" text ="Send" [isEnabled] ="fname.valid && lname.valid && email.valid && message.valid" (tap)="newContact(fname.value,lname.value,email.value,message.value)"></Button>
</FlexboxLayout>
services.ts
submitContact(first_name: string,last_name: string,email: string,message: string){
const body = JSON.stringify({first_name,last_name,email,message});
return this.http.post<ContactData>(this.url,body,{headers: this.headers});
}
.ts
newContact(firstName: string,lastName: string,message: string){
this.contactservices.submitContact(firstName,lastName,message).subscribe(
(_result) => this.router.navigate(["/home"]),(error) => console.log(error)
);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。