我想使用angular 2将数据发布到我的MMVC web api。但是我不知道如何使用angular将对象传递给我的MVC API。任何帮助都将不胜感激。
我在Angular 2中的服务代码
<rich:tabPanel>
我的MVC Api代码
@Injectable()
export class TaskService {
postitems(userId,username,userrole)
{
let data = {
"UserName": username,
"UserRole": userrole
}
let headers: {
'Content-Type': 'application/json; charset=utf-8', /*or whatever type is relevant */
'Accept': 'application/json'
}
//let body = JSON.stringify(data);
// let headers = new Headers({ 'Content-Type': 'application/json' ,'Accept': 'application/json'});
//let options = new RequestOptions({ headers: headers });
return this._http
.post('http://localhost:27353/api/Users',JSON.stringify(data), headers)
.toPromise()
.then(res => res.json().data)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.data || { };
}
Model.cs
[ResponseType(typeof(User))]
public IHttpActionResult PostUser(User user)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Users.Add(user);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = user.UserID }, user);
}
答案 0 :(得分:2)
我在没有测试您的解决方案的情况下看到的是您在从客户端传递到服务器的数据对象中错过了UserId。在restApi方法中,您还需要使用[FromBody]声明传递的对象User用户。
let data = {
"UserId": userId,
"UserName": username,
"UserRole": userrole
}
let headers = new Headers({ 'Content-Type': 'application/json' });
let body = JSON.stringify(data);
let options = new RequestOptions({headers: headers });
return this.http.post('http://localhost:27353/api/Users', body, options)
.toPromise()
.then(res => res.json().data)
.catch(this.handleError);
[ResponseType(typeof(User))]
public IHttpActionResult PostUser([FromBody]User user)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Users.Add(user);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = user.UserID }, user);
}
答案 1 :(得分:0)
您可能想要指定类型,因为它是打字稿。此外,注入HTTP服务以及我修复的一些其他打字稿问题,例如userID对于构造函数是可选的)。您还应该使用camelcase在JS中进行命名。
最后,在modal.cs中的部分类User中可以选择UserID,因为它不包括在内。
//Changes noted below
import { Http, Response } from '@angular/http';
export class TaskService {
//inject here
constructor(private http: Http, private res : Response) { }
//Important! (Make userId optionable if not inserted with the rest)
postitems: any (username: string, userrole: string, userId?: any) )
{
let data: any = {
"UserName": username,
"UserRole": userrole
}
let headers: any = {
'Content-Type': 'application/json; charset=utf-8', /*or whatever type is relevant */
'Accept': 'application/json'
}
//let body = JSON.stringify(data);
// let headers = new Headers({ 'Content-Type': 'application/json' ,'Accept': 'application/json'});
//let options = new RequestOptions({ headers: headers });
//let's use this extract Data method since it's here
private extractData(res: Response) {
let body = res.json();
return body.data || { };
}
return this._http
.post('http://localhost:27353/api/Users',JSON.stringify(data), headers)
.toPromise()
.then(data => extractData(data))
.catch(this.handleError);
}