首页 > 解决方案 > 将 JavaScript 对象转换为字符串

问题描述

我正在使用 Angular 8 开发一个项目,在该项目中我从 textArea 发布值并从 API 获取如下对象:API 响应,我正在尝试访问“raisonSociale”,但我找不到方法做

这是我的 http.post :

postResponse: any;

postRefs(){
return this.httpClient.post(this.url,this.datas)
  .subscribe(
    data => {
      console.log(data)
      const parsed = JSON.stringify(data)
      return this.postResponse = parsed;
    },
  );
 }

因此,我将来自 POST 的响应存储在 postReponse 中并尝试在我的 html 文件中呈现

         <tr>
          <td *ngIf="postResponse">{{postResponse.crossPart.all}}</td>
          <td *ngIf="postResponse">{{postResponse}}</td>
          <td *ngIf="postResponse">{{postResponse}}</td>
          <td *ngIf="postResponse">{{postResponse}}</td>
        </tr>

但在我的 HTML 中,它呈现如下:HTML 结果

我试过的:

我尝试不使用 const parsed :

postRefs(){
return this.httpClient.post(this.url,this.datas)
  .subscribe(
    data => {
      console.log(data)
      JSON.stringify(data)
      return this.postResponse = data;
    },
  );
}

以上返回我 [Object Object] :对象结果

提前感谢您的时间和帮助。

编辑 :

谢谢大家的回答!

@DmytroHuz 解决方案使它像魅力一样工作,这是需要做的:

        <tr *ngFor="let item of postResponse.crossPart.found">
          <td *ngIf="postResponse">{{item.articleSociete}}</td>
          <td *ngIf="postResponse">{{item.raisonSociale}}</td>
          <td *ngIf="postResponse">{{postResponse}}</td>
          <td *ngIf="postResponse">{{postResponse}}</td>
        </tr>

标签: javascriptjsonangularobject

解决方案


您正在尝试在您放入postResponse变量的 HTML 对象中进行设置。如果您需要响应中的某些特定值,则需要以如下方式调用它:postResponse.crossPart.all[0].raisonSociale. 或者你可以*ngFor使用postResponse.crossPart.all

<tr *ngFor="let item of postResponse.crossPart.all>
    <td *ngIf="postResponse">{{item.raisonSociale}</td>
          ...
</tr>

推荐阅读