Angular 11使用HTTP POST方法将数据提交到SQL Server数据库的示例:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class HttpService {
private url = 'http://localhost:5000/api/user'; // 这里的URL是调用Web API的URL
constructor(private http: HttpClient) { }
// 定义一个函数来向数据库提交数据
postUser(user: any): Observable {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
return this.http.post(this.url, user, httpOptions);
}
}
import { Component, OnInit } from '@angular/core';
import { HttpService } from 'src/app/services/http.service';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit {
// 创建一个空用户对象
user: any = {
name: '',
email: '',
phone: ''
};
constructor(private httpService: HttpService) { }
ngOnInit(): void {
}
// 当提交表单时,调用HTTP POST方法将用户数据提交到数据库中
onSubmit() {
// 调用httpService的postUser函数,将用户数据对象作为参数提交到数据库中
this.httpService.postUser(this.user).subscribe(res => {
console.log(res);
});
}
}
请确保在SQL Server中创建了适当的表单,并根据需要添加其他字段和验证。这个示例
上一篇:Angular11HTMLTemplatetoAngular
下一篇:Angular11InterceptorimplementationkeepsshowingTypescripterror