angular - 发布方法无法正常工作,没有任何错误
问题描述
我正在使用 angular 和 asp.net core webapi 创建一个简单的 crud 操作。当我尝试使用 value 来发布 value 时,它不起作用。
帖子组件:
<div class="col-md-4">
<form (ngSubmit)="validateuser()" #homeForm="ngForm">
<div class="form-group">
<label for="address">User Name</label>
<input type="text " min="0" class="form-control" [(ngModel)]="datas.username" name="username" required>
</div>
<div class="form-group">
<label for="address">Password</label>
<input type="text " min="0" class="form-control" [(ngModel)]="datas.password" name="password" required>
</div>
</form>
<div class="form-group">
<button type="submit" class="btn btn-success" [disabled]="!homeForm.form.valid">login</button>
</div>
</div>
服务 :
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { ViewEncapsulation } from '@angular/core';
import { UrlResolver } from '@angular/compiler';
import { Router } from '@angular/router';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
encapsulation: ViewEncapsulation.None
})
export class LoginComponent implements OnInit {
datas= {};
constructor(private http: HttpClient, private router: Router) { }
ngOnInit() {
}
validateuser() {
this.http.post('http://localhost:7254/api/user/token',this.datas)
.subscribe(res => {
console.log(res);
this.router.navigate(['/homes']);
}, (err) => {
this.router.navigate(['/login']);
}
);
}
}
API 控制器:
namespace WebAPI.Controllers
{
[Produces("application/json")]
[Route("api/User")]
public class UserController : Controller
{
private readonly ModelItemContext _context;
public UserController(ModelItemContext context)
{
_context = context;
}
[HttpPost("{token}")]
public ActionResult CreateToken([FromBody] User item_2)
{
var item_1 = _context.User.FirstOrDefault(t => t.UserName == item_2.UserName && t.Password == item_2.Password);
if (item_1 == null)
{
return NotFound();
}
_context.User.Update(item_1);
_context.SaveChanges();
return new NoContentResult();
}
}
}
当我尝试调试点时。该值未命中角度服务文件。这里有什么问题。请给我想法。同样的方法适用于创建用户。但是当我检查密码和用户名时不起作用。
解决方案
问题是您的数据变量是空对象。因此,如下所示声明数据变量,
datas: any = {
username: '',
password: ''
};
来自 UI 的帖子 URL 应该是 “ http://localhost:7254/api/User/token ”
并在 API 中更改您的CreateToken方法,例如,
[Route("token")]
public ActionResult CreateToken([FromBody]User item_2)
{
}
注意:在 HTML 中,在表单标签内添加按钮。
注意: API 中的用户模型应与角度模型匹配。
推荐阅读
- xml - 如何在 fiori 应用程序中动态隐藏片段字段
- html - 基于邮件的提交:不显示在电子邮件正文中
- javascript - 在切换中显示图像的边框
- batch-file - \* - \? 使用 xcopy (cmd)
- javascript - 如何修复while控制器中的Javascript错误?
- asp.net-core - Dotnetcore 2.2 应用程序无法启动
- angular - 全局变量在Angular 7的子功能中不起作用
- php - Wordpress 自定义字段顺序
- swift - 列出您附近的所有信标
- azure - 间歇性 HttpClient 问题 - SslStream 已处理