简体   繁体   中英

AngularJs 2: How to debug a service call? (es6 syntax)

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!

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM