Reputation: 21630
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!
Upvotes: 0
Views: 652
Reputation: 202276
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...
Upvotes: 2