简体   繁体   中英

Convert JavaScript Object to string

I'm working on a project in Angular 8 in which I post values from a textArea and get an Object as the following from an API: API response , I'm trying to access "raisonSociale" but I can't find a way to do it

Here's my 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;
    },
  );
 }

So, I store the response from POST in postReponse and try to render in my html file

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

But in my HTML it render as the following: HTML result

What I've tried:

I tried to without using const parsed:

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

The above returns me [Object Object]: Object result

Thank's for your time and your help in advance.

EDIT:

Thank you all for the answers!

@DmytroHuz solution made it work like a charm, here's what needed to be done:

        <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>

You are trying to set in your HTML object that you put into postResponse variable. If you need some particular value from your response, you need to call it in a way like: postResponse.crossPart.all[0].raisonSociale . Or you can use *ngFor for postResponse.crossPart.all

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

postResponse is an object, so when you access it in the HTML, it prints as object.

postResponse.crossPart.all is an array, so again it prints as object.

Specify the object property or loop in case of array to print primitive values

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM