Search code examples
angularangular2-services

http POST from body using multiple parameters


I have a method in ASP.Net Web API Controller as follows -

public string addNewTask([FromBody]TaskListModels _newTask)
        {
            DataTable _newTaskDataTable = new DataTable();
            try
            {
                SQLHelper sqlHelper = new SQLHelper(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString.ToString());
                sqlHelper.Parameters.AddWithValue("@taskId", _newTask.taskId);
                //sqlHelper.Parameters.AddWithValue("@userId", userId);
                sqlHelper.Parameters.AddWithValue("@taskDetails", _newTask.taskDetails);
                sqlHelper.Parameters.AddWithValue("@companyId", _newTask.companyId);
                sqlHelper.Parameters.AddWithValue("@dueDate", _newTask.dueDate);
                _newTaskDataTable = sqlHelper.ReturnDataTableFromStoredProcedure("[dbo].[MYSP]");
            }
            catch (SqlException ex)
            {
                Console.WriteLine("SQL ERROR: " + ex.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine("ERROR: " + e.Message);
            }

            return "String";
        }

Where TaskListModels is a class with some properties as follows.

public class TaskListModels
    {
        public int taskId { get; set; }
        public string userId { get; set; }
        public string taskDetails { get; set; }
        public int companyId { get; set; }
        public string companyName { get; set; }
        public string dueDate { get; set; }
    }

I am trying to post some data from an Angular service as follows -

 public addTask(_newTask: any) {
 console.log('Service - TaskListService : Method - addTask : Params - ' + JSON.stringify(_newTask))

this._requestOptions = new RequestOptions({
        method: RequestMethod.Post,
        url: this.addNewtaskApiUrl,
        headers: this.headers,
        body: JSON.stringify(_newTask)
    });
    console.log('ADD New - POST Request Query : ' + JSON.stringify(this._requestOptions));
    return this._http.request(new Request(this._requestOptions)).map(this._httpExtractDataService.extractData).catch(this._httpErrorHandlerService.handleError); 
}

The data appears in the browser console as follows but it is not hitting my controller method -

POST Request Query : {"method":1,"headers":{"Content-Type":["application/json"]},"body":"{\"taskId\":4,\"taskDetails\":\"Working with Avi for accounting platform project setup\",\"companyId\":4,\"dueDate\":\"2017-05-16\"}","url":"http://localhost:56250/api/Dashboard/addNewTask","withCredentials":null,"responseType":null}

Any help would be appreciated.

Thanks


Solution

  • Observables are by default cold. You need to subscribe to an observable to actually make a request:

    this._taskListService.addTask(this.newTask).subscribe((res)=>{
        console.log(res);
    });