【问题标题】:Angular 2 HTTP POST Call with parameters带有参数的Angular 2 HTTP POST调用
【发布时间】:2017-05-18 12:46:43
【问题描述】:

我有一个 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]");
                }
        ....
        ....

我有一个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); 
    }

其中LoginCredentialsModel是Model类如下--

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 参数显示为 null。 我还在控制台上记录了请求选项,如下所示,其中正文似乎是空的 {}。 获取任务列表 - POST 请求查询:

{"method":1,"headers":{"Content-Type":["application/json"]},"body":"{}","url":"http://localhost:8080/api/Dashboard/getTaskListByUserId","withCredentials":null,"responseType":null}

为什么没有发布参数?请帮忙。任何帮助将不胜感激。

谢谢, 阿米特·阿南德

【问题讨论】:

  • 您正在提供一个字符串参数'012345' 并尝试在您的方法中使用loginModel.userId 选择它的userId。你看到这里的复杂性了吗?
  • 我应该将它作为字符串传递而不是使用模型吗?

标签: angular angular2-services


【解决方案1】:

你是这样调用你的方法的:

this._taskListService.getTaskList('012345')...

但此方法需要一个对象 (LoginCredentialsModel)

因此,当您尝试在 getTaskList 方法中访问 loginModel.userId 时,它将未定义,因为您正在尝试访问 string 的属性。

解决方案可能是将其包装在一个对象中:

this._taskListService.getTaskList({userId: '012345'})...

【讨论】:

  • 您好!你知道这个问题的答案吗? stackoverflow.com/questions/44044163/…
  • 有什么方法可以避免 API 中的 [FromBody] 吗?我的意思是,如果我只是将 POST 参数作为(字符串 userId),那么将 Angular 服务中的 userId 简单地作为字符串发布而不使用任何模型的方式是什么?
【解决方案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' });

//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); 
    }

【讨论】:

  • 我也做了同样的事,但没有运气,现在 body 是这样的 "body":"userId=0500178" 但它仍然没有命中 API 方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多