0

THE SITUATION:

I am just learning Angular2. I wanted to debug the call to a service.

The service has been properly called, as I can see in the view.

I also want to log to content of variable that hold the result, but it is not working as i would except.

THE SERVICE:

export class ListService 
{
    getList() 
    {
        return Promise.resolve(LIST);
    }
}

THE CALL (from the list component):

export class ListComponent implements OnInit
{
    list: Item[];

    constructor(
        private _router: Router, 
        private _listService: ListService
    ) { }


    getList() 
    {
        this._listService.getList().then(list => this.list = list);
    }

    ngOnInit() 
    {
        this.getList();
    }

}

LOG ATTEMPT 1:

list is the variable containing the list of items. In the view it properly show the content. So i would expect to log it and see its content.

getList() 
{
    this._listService.getList().then(list => this.list = list);
    console.log(list)
}

But when i get this error instead:

EXCEPTION: ReferenceError: list is not defined in [null]

LOG ATTEMPT 2:

Trying to get the correct syntax:

getList() 
{
    this._listService.getList().then(list => this.list = list);
    console.log(this.list)
}

There are no errors now. But in the console it shows undefined. But the service has already been called. So it should contain the content

THE QUESTION:

Considering that i am using Angular2 - Ecmascript 2016

What is the proper syntax to log the call of a service?

Thank you!

FrancescoMussi
  • 20,760
  • 39
  • 126
  • 178
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Hacketo Mar 15 '16 at 12:35
  • Well this is more specific about Angular2 syntax – FrancescoMussi Mar 15 '16 at 12:39
  • The main issue is the same, this is not specific to any syntax, it's about how async task work and how you can work with it in javascript (BTW this is not Angular2 syntax but Ecmascript 6 the new Javascript standard) – Hacketo Mar 15 '16 at 12:40
  • Yes i got it. But if you just want to know just syntax for Angular2 you will find here the answer straightly. – FrancescoMussi Mar 15 '16 at 12:42
  • Well i edited the title. In order to make it more specific to this question. – FrancescoMussi Mar 15 '16 at 12:46

1 Answers1

2

In fact this.list is set within the callback registered in the then method. So you should use something like that:

getList() 
{
  this._listService.getList().then(list => {
    this.list = list;
    console.log(list);
    console.log(this.list);
  });
}

If you put the console.log(this.list); right the promise, the result won't be probably there so this.list probably doesn't set...

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360