首页 > 解决方案 > 角度未将主体传递给 PUT 方法

问题描述

我正在尝试创建一个 PUT 调用来更新英雄资源。

如果我将值硬编码为字符串并将其传入,则效果很好。(初始化并传入字符串 h 作为正文参数)

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json'
    , 'Access-Control-Allow-Origin': '*'
  })
};
   /** PUT: update the hero on the server */
  update(hero: Hero): Observable<any> {
    console.log('in  service.update');
    var h: string = '{id:28,name:"g-man",alterEgo:"jeff",superPower:"can fly"}';

    //hero
    return this.http.put(this.heroesUrl, h, httpOptions).pipe(
      tap(_ => this.log(`updated hero id=${hero.id}`)),
      catchError(this.handleError<any>('updateHero'))
    );
  }

但是,如果我让 Angular 传入 hero,则会调用 webservice 方法但没有参数。

 /** PUT: update the hero on the server */
      update(hero: Hero): Observable<any> {
        console.log('in  service.update');
        var h: string = '{id:28,name:"greg",alterEgo:"jeff",superPower:"eggs"}';

        //hero
        return this.http.put(this.heroesUrl, hero, httpOptions).pipe(
          tap(_ => this.log(`updated hero id=${hero.id}`)),
          catchError(this.handleError<any>('updateHero'))
        );
      }

这是webservice方法

   <HttpPut>
    <Route("")>
    Async Public Function update(<FromBody> mh As mHero) As Threading.Tasks.Task(Of CustomJsonStringResult)
        Dim requestBody As String = Await Request.Content.ReadAsStringAsync()
        Dim ag As New HeroSuperAg
        Dim h As Hero = ag.GetById(mh.id)
        h.name.Value = mh.name
        h.alterEgo.Value = mh.alterEgo
        h.superPower.Value = mh.superPower
        h.Save()
        Return JsonStringResultExtension.JSONString(Me, h.JSON, HttpStatusCode.OK)
    End Function

当我停止使用 Angular 发送参数的代码时,我可以检查 hero 并得到这个 检查英雄变量

但是该方法传递了一个为空的参数。

当我传入字符串时,传递了一个参数,它是我可以使用的正确 json hero 对象。

我已经检查了我的服务中请求对象的每个可用属性。无论是在 request.content 中还是在标头中,我都看不到内容。

我相信这可能会成为我需要传入的一些配置参数,但它正在逃避我。

这不是 CORS 问题。

为什么 Angular 不会将我的 FORM 变量的 JSON 表示传递回我的 Web 服务上的 PUT METHOD

这是 DevTools-Networking 选项卡 (Chrome) 的图片 在此处输入图像描述 这是在我按照建议将内容作为 JSON.stringify(hero) 传递之后

标签: javascriptangulartypescript

解决方案


我按照@Cyber​​Cyclist 和@PrishantPimpale 的建议将我的内容更改为JSON.Stringify(hero)。这解决了这个问题。

我按要求粘贴了网络截图。(我不知道这个调试资源......谢谢)

奇怪的是……我想完成这篇文章,看看它在错误状态下的样子,所以我把我的回调改为简单地传递 hero。现在我不能让它失败。

this.http.put(this.heroesUrl, hero, httpOptions)

and 

var hjson: string = JSON.stringify(hero)  this.http.put(this.heroesUrl, hjson, httpOptions)

两者都按预期工作。


推荐阅读