我想用angular和asp做一个服装店,但是我遇到了将数据发送到数据库的困难。有一个用于注册和授权的模块化表格。首先,我决定实现注册表单,但是发送数据时出错:
我是新手,所以我附上了代码,因为我不知道错误的问题是什么。
用户.ts:
export class Users{
id? = "";
phone = "";
email = "";
fio = "";
address ="";
password = "";
}
用户服务.ts:
@Injectable({
providedIn: 'root'
})
export class UserServiceService {
private url = "User";
constructor(private http: HttpClient) {
}
@Input() public createUser(users: Users): Observable<Users> {
return this.http.post<Users>(
`${environment.apiUrl}/${this.url}`,
users
);
导航菜单.ts:
export class NavMenuComponent {
user:Users =new Users;
@Output() userUpdated = new EventEmitter<Users>();
constructor(private superHeroService: UserServiceService) {}
createnewUser(users: Users) {
this.superHeroService
.createUser(users)
.subscribe((users: Users) => this.userUpdated.emit(users));
}
}
从输入中读取变量:
<div class="modal-body">
<input [(ngModel)]="user.email" class="form-control">
<input [(ngModel)]="user.phone" class="form-control">
<input [(ngModel)]="user.address" class="form-control">
<input [(ngModel)]="user.fio" class="form-control">
<input type="password" [(ngModel)]="user.password" class="form-control"> :
<input type="password" class="form-control">
</div>
后端:
用户控制器.cs:
[Route("api/[controller]")]
[ApiController]
public class UserController : Controller
{
private readonly DataContext _context;
public UserController(DataContext context)
{
_context = context;
}
[HttpPost]
public async Task<IActionResult> CreateUser(User user)
{
_context.Users.Add(user);
await _context.SaveChangesAsync();
return Ok(await _context.Users.ToListAsync());
}
}
数据上下文.cs:
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) : base(options)
{
Database.EnsureCreated();
}
public DbSet<User> Users => Set<User>();
}
User.cs:公共类用户
{
public string? Id = string.Empty;
public string Phone = string.Empty;
public string Email = string.Empty;
public string FIO = string.Empty;
public string Password = string.Empty;
}
用户.cs: