John
John

Reputation: 301

Cannot set results of an api call to a variable in an Angular 1 application

I am trying to call an api, and set the results to a variable. I am able to successfully make the call and see the data when I log it in the console, but later when I try to use the variable it is undefined.

Here is the relevant code:

        var postParams = {
            "code": input.Code,
            "number": input.Number
        }

        var result;

        try {
            $http.post("/api/DetailAPI/GetDetails?code=" + input.Code + "&number=" + input.Number, postParams).success(function (details) {
                console.log(details);
                result = JSON.parse(details);
            });
        }
        catch (error) {
            console.log(error);
        }

        console.log(result);

The first console.log(details) shows the data I am expecting listed as "Object". When console.log(result) is called result is undefined.

I have tried with and without JSON.parse() and get the same result either way.

I know the api call is working, since I can see the data in the console. The issue is that I cannot store this data in my result variable.

How do I get Angular to actually put the data I get from the api call into a variable?

Upvotes: 0

Views: 556

Answers (1)

Akash AR
Akash AR

Reputation: 39

You are consoling the result variable before it has been defined.

Upvotes: 1

Related Questions