Test admin
Test admin

Reputation: 731

Angular2 http response undefined

This is my server data:

[
    {
        "name" : "testname"
    },
    {
        "name" : "testnametwo"
    }
]

I am trying to get this data using Angular2 http.get. I am trying with below code:

private _url : string = "appone/api/user.json"

    user = []

    constructor(private http : Http) { }

    getUsers() {
        let res = this.http.get(this._url).map((response : Response) => {
            return response.json()
        })
        res.subscribe((data) => {
            this.user = data
        })

        alert(this.user.name)
    }

But I didn't get any result. I don't know where I am wrong.

Any help is greatly appreciated.

Upvotes: 0

Views: 486

Answers (2)

Sangram Nandkhile
Sangram Nandkhile

Reputation: 18192

Your alert needs to be placed inside subscribe.

getUsers() {
        let res = this.http.get(this._url).map((response : Response) => {
            return response.json()
        })
        res.subscribe((data) => {
            this.user = data;
           alert(this.user.name); 
        })

    }

Explanation: Your API will probably take some time to return data and it will be called asynchronously. So your alert will be called even before your data has been returned by API.

Subscribe will be called only when it gets data from API so it is an appropriate place to log. Also, do consider logging errors as a good practice.

Upvotes: 1

Andy Lamb
Andy Lamb

Reputation: 2242

The code subscribes to the response and will set this.user when the the http.get returns asynchronously. So the alert will fire before the user is set.

Upvotes: 0

Related Questions