Rosenberg
Rosenberg

Reputation: 2444

Angular 6 - Reading JSON response from a POST

  this.http.post('http://localhost:1337/upload', formData, httpOptions)
    .subscribe( res => {
      console.log(res)
    })

The code above is working just fine, however, I don't know how to read the response.

This is the response I get:

[ { "_id": "5b588e82dfba462415d68d67", "name": "portal.jpg", "hash": "565a716df5de4d968779bffd6b99668a", "ext": ".jpg", "mime": "image/jpeg", "size": "976.35", "url": "http://localhost:1337/uploads/565a716df5de4d968779bffd6b99668a.jpg", "provider": "local", "related": [], "createdAt": "2018-07-25T14:51:46.012Z", "updatedAt": "2018-07-25T14:51:46.024Z", "__v": 0, "id": "5b588e82dfba462415d68d67" } ]

I specifically need to read url and set it to a variable, how can I do that?

Upvotes: 0

Views: 2641

Answers (3)

David R
David R

Reputation: 15639

In your component .ts file have a variable named uploadUrl and assign it as,

this.http.post('http://localhost:1337/upload', formData, httpOptions)
    .subscribe( res => {
       this.uploadUrl = res[0].url;
    })

Hope this helps!

Upvotes: 4

Nicholas Pipitone
Nicholas Pipitone

Reputation: 4142

myurl = res[0]["url"]

should work. Try console.log(res[0]) to understand why we need res[0]. It uses the same syntax behind

arr = [0, 1, 2, 3] console.log(arr[2]) // 2

Make sure to define myurl before this.http.post.

Upvotes: 2

Taranjit Kang
Taranjit Kang

Reputation: 2580

It seems like you're sending back an array, so probably:

.subscribe( (res: any)=> {
   res[0].url

Of course this would get the first value of the response, either send no array and just the object or loop through the response if more than one object and retrieve the urls.

Also, you could add a type to your response for intellisense, create a model and then add

 .subscribe( (res: TheModelYouCreated)=> {

Upvotes: 3

Related Questions