0

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.