[英]AngularJs 2: How to debug a service call? (es6 syntax)
THE SITUATION: 情况:
I am just learning Angular2. 我只是在学习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: 日志尝试1:
list
is the variable containing the list of items. list
是包含项目list
的变量。 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: 日志尝试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
. 但是在控制台中,它显示undefined
。 But the service has already been called. 但是该服务已被调用。 So it should contain the content 所以它应该包含内容
THE QUESTION: 问题:
Considering that i am using Angular2 - Ecmascript 2016 考虑到我正在使用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. 实际上, this.list
是在then
方法中注册的回调中设置的。 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);
如果放置console.log(this.list);
right the promise, the result won't be probably there so this.list
probably doesn't set... 正确的承诺,结果可能不会在那里,所以this.list
可能没有设置...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.