Angular 2 HTTP POST 带参数调用
Angular 2 HTTP POST Call with parameters
我有一个 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]");
}
....
....
我有一个Angular2服务方法如下--
//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);
}
其中 LoginCredentialsModel 是一个模型 class 如下 --
export class LoginCredentialsModel {
userId: any;
}
我正在从我的组件之一调用服务方法以从 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)));
}
POST 调用能够到达 API 方法,但由于某种原因,当我调试 API 时,userId 参数显示为空。
我还在控制台上记录了请求选项,如下所示,主体似乎为空 {}。
获取任务列表 - POST 请求查询:
{"method":1,"headers":{"Content-Type":["application/json"]},"body":"{}","url":"http://localhost:8080/api/Dashboard/getTaskListByUserId","withCredentials":null,"responseType":null}
为什么没有发布参数?请帮忙。任何帮助将不胜感激。
谢谢,
阿米特·阿南德
您需要对您的代码进行一些更改
//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);
}
您正在这样调用您的方法:
this._taskListService.getTaskList('012345')...
但此方法需要一个对象 (LoginCredentialsModel
)
因此,当您尝试在 getTaskList
方法中访问 loginModel.userId
时,它将是未定义的,因为您正在尝试访问 string
的 属性。
一个解决方案可能是将其包装在一个对象中:
this._taskListService.getTaskList({userId: '012345'})...
我有一个 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]");
}
....
....
我有一个Angular2服务方法如下--
//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);
}
其中 LoginCredentialsModel 是一个模型 class 如下 --
export class LoginCredentialsModel {
userId: any;
}
我正在从我的组件之一调用服务方法以从 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)));
}
POST 调用能够到达 API 方法,但由于某种原因,当我调试 API 时,userId 参数显示为空。 我还在控制台上记录了请求选项,如下所示,主体似乎为空 {}。 获取任务列表 - POST 请求查询:
{"method":1,"headers":{"Content-Type":["application/json"]},"body":"{}","url":"http://localhost:8080/api/Dashboard/getTaskListByUserId","withCredentials":null,"responseType":null}
为什么没有发布参数?请帮忙。任何帮助将不胜感激。
谢谢, 阿米特·阿南德
您需要对您的代码进行一些更改
//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);
}
您正在这样调用您的方法:
this._taskListService.getTaskList('012345')...
但此方法需要一个对象 (LoginCredentialsModel
)
因此,当您尝试在 getTaskList
方法中访问 loginModel.userId
时,它将是未定义的,因为您正在尝试访问 string
的 属性。
一个解决方案可能是将其包装在一个对象中:
this._taskListService.getTaskList({userId: '012345'})...