0

现象:AngularJs 2:如何调试服务调用? (es6语法)

我刚刚学习Angular2。我想调试一个服务的调用。

该服务已被正确调用,正如我在视图中所见。

我也想登录到保存结果的变量的内容,但它不工作,因为我会除外。

该服务:

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

呼叫(从列表组件):

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是包含可变项目列表。在视图中正确显示内容。所以我希望能够记录下来,看看它的内容。

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

但是,当我得到这个错误,而不是:

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

LOG未遂2:

试图获得正确的语法:

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

有没有错误现在。但在控制台中显示undefined。 但服务已被调用。所以,它应该包含内容

问题:

考虑到我使用Angular2 - 的EcmaScript 2016

什么是正确的语法登录服务的电话吗?

谢谢!

+2

的可能的复制[如何我是否返回来自异步调用的响应?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Hacketo

+0

那么这是更具体关于Angular2语法 – johnnyfittizio

+0

主要问题是相同的,这不是特定于任何语法,它是关于异步任务如何工作,以及如何使用它在JavaScript中工作(顺便说一句,这不是Angular2语法,而是Ecmascript 6新的Javascript s标准) – Hacketo

回答

2

实际上this.list设置在then方法中注册的回调中。所以,你应该使用这样的事情:如果你把console.log(this.list);权的承诺

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

,结果会不会可能有这么this.list可能不会设置...