2017-02-13 96 views
0

我有一個非常簡單的測試組件,它看起來是這樣的:角2局部變量認購()方法

@Component({ 
    selector: "test-component", 
    template: "<div>Test</div>", 
}) 
export class TestComponent implements OnInit { 
    private test : number = 0; 
    private service : ClientsService; 

    constructor(s : ClientsService) { 
     this.service = s; 
    } 

    public ngOnInit() { 
     this.service.loadAllClients().subscribe(d => { 
      this.test = 1; 
     }); 
     let comp = this; 
    } 
} 

客戶服務返回可觀察到的,但我的問題是關於「測試」變量。在組件加載之後,第一個和第一個斷點被命中,'test'的值爲0 enter image description here 但是,當'subscribe()'中的斷點被命中時,'test'變得未定義。在lambda內完成的任何分配都不會生效。 enter image description here

我在這裏錯過了在'subscribe()'中做適當的賦值?

+0

我不認爲你錯過了任何東西。我認爲通過編譯TypeScript獲得的實際JavaScript代碼使用另一個不是'this'的變量來引用回調中的組件。在控制檯中打印該值,並查看它是否正確打印。 –

回答

1

有一種可能性(我不確定)是this正在對該服務進行作用域化,因爲您的組件中已聲明瞭它的一個實例。我自己並沒有這樣做,所以我不確定。你可以試試看看它是否有效:

@Component({ 
    selector: "test-component", 
    template: "<div>Test</div>", 
}) 
export class TestComponent implements OnInit { 
    private test : number = 0; 

    constructor(private _service : ClientsService) {} 

    public ngOnInit() { 
     this._service.loadAllClients().subscribe(d => { 
      this.test = 1; 
     }); 
     let comp = this; 
    } 
} 

除此之外,沒有什麼看起來不對我。我已經多次使用上述方法,並已正確保存了組件範圍的this

+0

謝謝大家。原來,這個任務工作正常,但有一些有趣的事情發生在Webstorm,我們正在使用的IDE,正在調試代碼 – Andrey

+0

更多人需要知道這個答案。我浪費了整整一個工作日試圖弄清楚這一點。 –