2

I am working on Angular 2 technology, in one of my current project I was faced the issue in HTTTP POST request using typescript code.

This is the code I wrote in myservice.ts

 postVehicleInfoRestful(vehicleInfo: VehicleInfoTable): Observable<VehicleInfoTable> {

    console.log('VehicleInfo Service.')

    //let body = JSON.stringify(vehicleInfo ? vehicleInfo  : null);
    let body = JSON.stringify(vehicleInfo);
    console.log(body);

    let headers = new Headers({
        'Content-Type': 'application/x-www-form-urlencoded'
    }); //'application/x-www-form-urlencoded' application/json


    let options = new RequestOptions({ headers: headers });//, method: "post"

    console.log(this._settingsService.todoListAPIUrl + '/api/VehicleInfoTable');

    return this._http.post(this._settingsService.todoListAPIUrl + '/api/VehicleInfoTable', body, options)
        .map(res => res.json())
        .do(data => console.log(JSON.stringify(data)))
        .catch(this.handleError);
}

And also, wrote the code in mycomponenet.ts

ngOnInit(): void {

    console.log(' VehicleInfoComponent In OnInit');

    this.vehicleInfo.ID = 7;
    this.vehicleInfo.AssetType = 'Auto';
    this.vehicleInfo.IntendedUse = 'Personal';
    this.vehicleInfo.NeworUsed = 'New';
    this.vehicleInfo.SSN = '123456789';
    this.vehicleInfo.VehicleYear = '1';
    this.vehicleInfo.VehicleMake = '2';
    this.vehicleInfo.VehicleModel = '3';
    this.vehicleInfo.VIN = 'US123';
    this.vehicleInfo.CurrentMileage = '40';             
}

 saveVehicleInfo() {

    console.log('Save Vehicle Info Details.');
    console.log(this.vehicleInfo);

    this._vehicleInfoService.postVehicleInfoRestful(this.vehicleInfo).subscribe(//call the post
        data => this.postVehicleInfoToServer = JSON.stringify(data),// put the data returned from the server in our variable
        error => console.log("Error HTTP Post Service"),// in case of failure show this message
        () => console.log("Job Done Post !"));  //run this code in all cases   

}

This is the code I wrote in mycontroller.cs

 public async Task Post(VehicleInfoTable vehicleInfo)
    {
        try
        {
            //owner = ((ClaimsIdentity)User.Identity).FindFirst(ClaimTypes.NameIdentifier).Value;

            using (var client = NewDataAPIClient())
            {
                await client.VehicleInfoTables.PostVehicleInfoTableByVehicleinfotableAsync(new VehicleInfoTable
                {

                    ID = (int)vehicleInfo.ID,
                    AssetType = vehicleInfo.AssetType,
                    IntendedUse = vehicleInfo.IntendedUse,
                    NeworUsed = vehicleInfo.NeworUsed,
                    SSN = vehicleInfo.SSN,
                    VehicleYear = vehicleInfo.VehicleYear,
                    VehicleMake = vehicleInfo.VehicleMake,
                    VehicleModel = vehicleInfo.VehicleModel,
                    VIN = vehicleInfo.VIN,
                    CurrentMileage = vehicleInfo.CurrentMileage
                });
            }
            System.Diagnostics.Trace.TraceInformation("VehicleInfoTableController in ToDoListAPI");
            DevInsights.TrackEvent("VehicleInfoTableController in ToDoListAPI", "Post");

        }
        catch (Exception ex)
        {
            DevInsights.TrackException(ex, "VehicleInfoTableController in ToDoListAPI", "Post");
            System.Diagnostics.Trace.TraceWarning(ex.Message);
        }
    }

when I debug my code, once click on save button, based on my post url this method will fired public async Task Post(VehicleInfoTable vehicleInfo) { ...... } but in that vehicleInfo parameter contains all fields value will be null but when I make post request I added the data in the body.

Can you please tell me where I did mistake for adding the data to body in http post request.

enter image description here

Can you please tell me where I did mistake and how can I resolve this issue?

-Pradeep

2
  • When the post request fails, what is the error you receive? Commented Jan 6, 2017 at 12:36
  • Thanks, can you please see my updated question once. Commented Jan 6, 2017 at 12:47

2 Answers 2

2

EDIT I could suggest two options for you to try, either:

Try this, make it as simple as possible first, then try to add more moving parts ;)

postVehicleInfoRestful(vehicleInfo: VehicleInfoTable) {
    let body = JSON.stringify(vehicleInfo);
    let headers = new Headers({
    'Content-Type': 'application/json'}); 
    let options = new RequestOptions({ headers: headers });
    return this._http.post(this._settingsService.todoListAPIUrl + '/api/VehicleInfoTable', body, options)
      .map((res: Response) => { console.log('res', res); }) // let's see what we get
}

or:

postVehicleInfoRestful(vehicleInfo: VehicleInfoTable) {
    let body = new URLSearchParams();
    // mark all your properties and values below with body.set
    body.set('yourPropertyName1', vehicleInfo.property1)
    body.set('yourPropertyName2', vehicleInfo.property2)
    let headers = new Headers({
    'Content-Type': 'application/x-www-form-urlencoded'}); 
    let options = new RequestOptions({ headers: headers });
    return this._http.post(this._settingsService.todoListAPIUrl + '/api/VehicleInfoTable', body.toString(), options)
      .map((res: Response) => { console.log('res', res); }) // let's see what we get
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I updated my code with above lines but it won't works ,it gives exception like "OPTIONS localhost:46439/api/VehicleInfoTable 405 (Method Not Allowed)", XMLHttpRequest cannot load localhost:46439/api/VehicleInfoTable. Response for preflight has invalid HTTP status code 405.
Updated my answer, try the second one... no idea if that would work, but you can try :)
0

Calling map(res => console.log(res.json())) on the Observable in myservice.ts is mapping the result to type void. Correct to map(res => res.json()) instead. The RXJS Observable do(...) method is designed exactly for this purpose, as it does not affect the Observable's contents.

5 Comments

Thanks, I updated my code with what you said above, but still also facing the same issue as it's return null value.
Did you inspect the server's response externally to ensure the response's body content is not null?
Thanks , can you please see my updated question once.
I doubt this error is on the Angular side. If you have corrected the map(...) issue then Angular will simply return the HTTP post response body as an object. Since there is no error, it is most likely that your controller is returning an empty response body.
Thanks, I corrected the map(....) issue but once post request fired my controller method in that vehicleinfo contains null value. I don't know how it be null even I supplied the data in http post request.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.