簡體   English   中英

HTTP POST請求失敗,使用打字稿在Angular 2中以空值作為響應

[英]HTTP POST request failed with response as null values in angular 2 using typescript

我正在研究Angular 2技術,在我當前的項目之一中,我遇到了使用打字稿代碼的HTTTP POST請求中的問題。

這是我在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);
}

並且,在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   

}

這是我在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);
        }
    }

當我調試代碼時,一旦單擊保存按鈕,基於我的發布網址,此方法將觸發公共異步任務發布(VehicleInfoTable vehicleInfo){......},但其中的vehicleInfo參數包含所有字段,值將為null,但當我發出發布請求時,我在主體中添加了數據。

您能告訴我在http帖子請求中將數據添加到正文時我在哪里犯了錯誤。

在此處輸入圖片說明

您能告訴我我在哪里做錯了,如何解決這個問題?

-Pradeep

編輯我可以建議您嘗試兩個選項,或者:

嘗試一下,首先使其盡可能簡單,然后嘗試添加更多的運動部件;)

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
}

要么:

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
}

myservice.ts的Observable上調用map(res => console.log(res.json()))結果映射為void類型。 更正為map(res => res.json()) RXJS Observable do(...)方法正是為此目的而設計的,因為它不會影響Observable的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM