Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Angular Convert POST request data to array

Hello so i have a post request that sends some data to a NodeJS app and then that returns an array. My problem is that i cant turn the data i receive as a response from the POST request to an array.
My Angular is set up like this:

newWord = '';
  keyword = '';

  onClick() {
    const headers = new HttpHeaders()
      .set('Authorization', 'my-auth-token')
      .set('Content-Type', 'application/json');

    this.http.post('http://localhost:3000/search',
      { keyword: this.keyword },
      {
        headers: headers
      })
      .subscribe((data) => {
        console.log(data);
      })
  }
}

The data inside the node app looks like this:
enter image description here

I want to get this data in angular as an array so i can itterate through it or do anything else with the fields. Any help would be appreciated!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Provide the type to the http request. Otherwise angular expects any, which is not necessarily an array. That is where the error comes from.

 this.http.post<{ id: string, text: string }[]>('http://localhost:3000/search',
      { keyword: this.keyword },
      {
        headers: headers
      })
      .subscribe((data) => {
        console.log(data);
      })
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading