[英]Angular 2 HTTP POST Call with parameters
I have a ASP.Net Web API method as follows -- 我有一个ASP.Net Web API方法如下 -
public class DashboardController : ApiController
{
[HttpPost]
public TaskListModels[] getTaskListByUserId([FromBody] LoginModels loginModels)
{
DataTable _taskListDataTable = new DataTable();
List<TaskListModels> _taskList = new List<TaskListModels>();
try
{
if(!string.IsNullOrEmpty(loginModels.userId))
{
SQLHelper sqlHelper = new SQLHelper(ConfigurationManager.ConnectionStrings["Hr_Platform_Dev_ConnString"].ConnectionString.ToString());
sqlHelper.Parameters.AddWithValue("@userId", loginModels.userId);
_taskListDataTable = sqlHelper.ReturnDataTableFromStoredProcedure("[dbo].[HRPlatform_Dashboard_Tasklist_Select]");
}
....
....
I have an Angular 2 service method as follows -- 我有一个Angular 2服务方法如下 -
//Get Task List of a User
public getTaskList(loginModel: LoginCredentialsModel): Observable<TaskListModel[]>{
console.log('Service - TaskListService : Method - getTaskList : Params - ' + loginModel.userId);
let headers = new Headers({ 'Content-Type': 'application/json' });
this._requestOptions = new RequestOptions({
method: RequestMethod.Post,
url: this._httpHelperService.apiUrl + 'Dashboard/getTaskListByUserId',
headers: headers,
body: JSON.stringify({ 'userId': loginModel.userId })
});
console.log('Get Task List - POST Request Query : '+JSON.stringify(this._requestOptions));
return this._http.request(new Request(this._requestOptions)).map(this._httpHelperService.extractData).catch(this._httpHelperService.handleError);
}
Where LoginCredentialsModel is a Model class as follows -- LoginCredentialsModel是Model类,如下所示 -
export class LoginCredentialsModel {
userId: any;
}
I am calling the service method from one of my component to get the data from the API method as follows -- 我从我的一个组件调用服务方法来从API方法获取数据,如下所示 -
public loadTask()
{
console.log('Component : Dashboard Component - Method : loadTask');
//Set the current
this._taskListService.getTaskList('012345').subscribe(
data => this.taskListItems = data,
error => this._errorLoggerService.logError(error, 'Dashboard/TaskList Component'),
() => console.log("Task List For User Id - 012345 + "\n" + JSON.stringify(this.taskListItems)));
}
The POST call is able to reach the API method but for some reason the userId parameter is appearing as null when I am debugging the API. POST调用能够到达API方法,但由于某种原因,当我调试API时,userId参数显示为null。 I have also logged the request option on the console that looks like follows, where it appears that that the body is empty {}.
我还在控制台上记录了如下所示的请求选项,其中看起来正文为空{}。 Get Task List - POST Request Query :
获取任务列表 - POST请求查询:
{"method":1,"headers":{"Content-Type":["application/json"]},"body":"{}","url":"http://localhost:8080/api/Dashboard/getTaskListByUserId","withCredentials":null,"responseType":null}
Why the parameters are not getting posted ? 为什么没有发布参数? Please help.
请帮忙。 Any Help would be appreciated.
任何帮助,将不胜感激。
Thanks, Amit Anand 谢谢,Amit Anand
In your code you need to do some change 在您的代码中,您需要做一些更改
//Get Task List of a User
public getTaskList(loginModel: LoginCredentialsModel): Observable<TaskListModel[]>{
console.log('Service - TaskListService : Method - getTaskList : Params - ' + loginModel.userId);
let headers = new Headers({ 'Content-Type': 'application/json' });
//instead of JSON.stringify try this
var postdata = "userId="+loginModel.userId;
this._requestOptions = new RequestOptions({
method: RequestMethod.Post,
url: this._httpHelperService.apiUrl + 'Dashboard/getTaskListByUserId',
headers: headers,
body: postdata
});
console.log('Get Task List - POST Request Query : '+JSON.stringify(this._requestOptions));
return this._http.request(new Request(this._requestOptions)).map(this._httpHelperService.extractData).catch(this._httpHelperService.handleError);
}
You are calling your method like this: 你正在调用你的方法:
this._taskListService.getTaskList('012345')...
but this method expects an object ( LoginCredentialsModel
) 但是这个方法需要一个对象(
LoginCredentialsModel
)
So when you try to access loginModel.userId
inside your getTaskList
method it will be undefined because you are trying to access a property of a string
. 因此,当您尝试访问
loginModel.userId
方法中的getTaskList
,它将是未定义的,因为您正在尝试访问string
的属性。
A solution might be to wrap it in an object: 解决方案可能是将其包装在对象中:
this._taskListService.getTaskList({userId: '012345'})...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.