2016-04-06 33 views
2

有什麼辦法來檢查是否有計劃的任務使用Angular2和Zone.js?檢查是否有計劃的任務與Angular2和Zone.js

比方說,我有這個分量

import... 

@Component({...}) 
export class MyComponent { 

    public myMethod() { 
    console.log('enter my method'); 
    setTimeout(function() { console.log('task1'); }, 1000); 
    setTimeout(function() { console.log('task2'); }, 1500); 
    } 

} 

,我希望當兩個task1task2完成通知。

在我的應用程序組件我訂閱onUnstableonStable事件是這樣的:

@Component({ 
    selector: 'app', 
    directives: [MyComponent], 
    template: `<mycmp></mycmp>` 
}) 
export class AppComponent { 

    constructor(private zone:NgZone) { 
    console.log('start app component constructor'); 

    zone.onUnstable.subscribe(function(args){ 
     console.log('enter unstable'); 
    }); 

    zone.onStable.subscribe(function(args){ 
     console.log('enter stable'); 
    }); 
    } 
} 

所以,當我打電話myMethod()我所期望的是此序列的日誌:

enter unstable 
enter my method 
task1 
task2 
enter stable 

但我得到這個:

enter unstable 
enter my method 
enter stable 
enter unstable 
task1 
enter stable 
enter unstable 
task2 
enter stable 

回答

0

讓我試着解釋t他的結果。

這裏共有三個微觀任務。

任務1

public myMethod() { ... }

任務2

setTimeout(function() { console.log('task1'); }, 1000);

任務3

setTimeout(function() { console.log('task2'); }, 1500);

前三行相關的Task1開始和完成。

接下來的三行與Task2的開始和結束有關。

最後三行與Task3的開始和結束有關。

每個異步操作,包括可以調用myMethod創建一個新的microtask

+0

好事件處理中,爲什麼我得到的日誌是明確的,但是,有沒有得到通知,一旦所有三個任務完成的方法嗎? – Gigitsu