0

I am trying to populate items from the returned async call.

this._service.getAll()
        .subscribe(
            data => {
                this.items = data.map(function (item) {
                    return { a: item.a, b: item.b };
                }, error => console.error('error: ', error))
        });

console.log(items);

Being async call, the assignation is not happening immediately and therefore I am not getting the values in items in the next line of code, as such console.log(items) prints null.

How do I make sure that items is not null.

2
  • your console.log executed before your service Commented May 31, 2017 at 11:58
  • yes that is actually happening. thank you. how to make the console.log execute after the service call Commented May 31, 2017 at 12:07

1 Answer 1

1

You can't. You have to consume the items inside the callback. You can however use variables from the outside scope inside the callback, which is why you can assign them to this.items.

I would mention that, of course items will always be null, you may have more luck with this.items (though not just after the subscribe). However, as far as angular is concerned, when you assign items to the property, components will be rerendered with the updated data.


There are some experimental technologies that allow you to write asynchronous code in a synchronous manner, await, but it requires that you write the code slightly differently (principally marking the functions in which you use await as async).

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

2 Comments

Yes in the view it is working. but I want to assign a variable at constructor from the api call. How can this be achieved?
Can you tell me in more details how it can be achieved using callback. I tried multiple ways but it is not working at all. I am using the variable to populate a control where it is going as null value.

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.