【问题标题】:HTTP POST request failed with response as null values in angular 2 using typescriptHTTP POST 请求失败,使用打字稿在角度 2 中响应为空值
【发布时间】:2017-01-06 12:22:59
【问题描述】:

我正在研究 Angular 2 技术,在我当前的一个项目中,我遇到了使用打字稿代码的 HTTP 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);
        }
    }

当我调试我的代码时,一旦点击保存按钮,根据我的帖子网址,此方法将触发 public async Task Post(VehicleInfoTable vehicleInfo) { …… } 但是在那个 vehicleInfo 参数包含所有字段的值将是 null 但是当我发出发布请求时,我在正文中添加了数据。

您能告诉我在 http post 请求中将数据添加到正文中出错的地方吗?

你能告诉我我在哪里做错了吗?我该如何解决这个问题?

-Pradeep

【问题讨论】:

  • post请求失败时,你收到的错误是什么?
  • 谢谢,你能不能看一下我更新的问题。

标签: angular http-post typescript2.0


【解决方案1】:

编辑我可以建议您尝试两个选项:

试试这个,先让它尽可能简单,然后再尝试添加更多活动部件;)

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
}

【讨论】:

  • 谢谢,我用上面几行更新了我的代码,但它不起作用,它给出了“OPTIONS localhost:46439/api/VehicleInfoTable 405(不允许的方法)”之类的异常,XMLHttpRequest 无法加载localhost:46439/api/VehicleInfoTable。预检响应包含无效的 HTTP 状态代码 405。
  • 更新了我的答案,试试第二个......不知道这是否可行,但你可以试试:)
【解决方案2】:

myservice.ts 中的 Observable 上调用 map(res =&gt; console.log(res.json())) 会将结果映射到类型 void。改为更正map(res =&gt; res.json())。 RXJS Observable do(...) 方法正是为此目的而设计的,因为它不会影响 Observable 的内容。

【讨论】:

  • 谢谢,我用你上面所说的更新了我的代码,但仍然面临同样的问题,因为它返回 null 值。
  • 您是否在外部检查了服务器的响应以确保响应的正文内容不为空?
  • 谢谢,你能不能看看我更新的问题一次。
  • 我怀疑这个错误是在 Angular 方面。如果您已经更正了 map(...) 问题,那么 Angular 将简单地将 HTTP 发布响应正文作为对象返回。由于没有错误,很可能您的控制器返回的是空响应正文。
  • 谢谢,我更正了 map(....) 问题,但是一旦发布请求触发了我的控制器方法,其中的 vehicleinfo 包含空值。即使我在 http post 请求中提供了数据,我也不知道它是如何为空的。
猜你喜欢
  • 1970-01-01
  • 2012-04-08
  • 1970-01-01
  • 2017-05-04
  • 2020-11-17
  • 2016-12-02
  • 2020-04-05
  • 1970-01-01
  • 2012-12-17
相关资源
最近更新 更多