2015-12-14 44 views
0

我有一個Angular 2組件,它顯示項目列表,並註冊到發佈事件的服務。問題是即使我在收到一個事件時沒有做任何事情,Angular也會更新視圖(或者至少在我猜測它不應該做什麼時)。Angular2組件視圖不斷更新

Here is a plunker

正如您在控制檯中所看到的,每次我的服務發佈消息時,都會調用我的項目的「getTitle()」方法。

即使我沒有註冊到我的服務,並且如果我的組件沒有實現MyServiceListener接口,每次服務獲取消息時都會調用getTitle。如果我沒有在構造函數中給我的組件提供服務,那麼一切都很好。所以,我的依賴注入有些問題,但是什麼?

這裏是plunker的相關代碼:

我的服務和其偵聽器接口:

export interface MyServiceListener { 

    onMessage(_message: any); 
} 

export class MyService { 

    private m_listener: MyServiceListener; 

    constructor() { 

      window.setInterval(() => { 

       if (this.m_listener !== undefined) { 

        this.m_listener.onMessage("Hi"); 
       } 

      }, 500); 
    } 

    setListener(_listener: MyServiceListener) { this.m_listener = _listener; } 
} 

Item類:

export class Item { 

    m_title: string; 

    constructor(_title: string) { 

     this.m_title = _title; 
    } 

    getTitle(): string { console.log("getTitle"); return this.m_title; } 
} 

我的組件:

@Component({ 
    selector: 'my-app', 
    template : ` 
     <div> 
      <ul> 
       <li *ng-for="#item of m_items"> 
        {{item.getTitle()}} 
       </li> 
      </ul> 
     </div> 
    ` 
}) 
export class App implements TestBugAngularServiceListener { 

    private m_items: Array<Item> = new Array<Item>(); 

    constructor(_communicationService: MyService) { 

     this.m_items.push(new Item("A")); 
     this.m_items.push(new Item("B")); 
     this.m_items.push(new Item("C")); 

     _communicationService.setListener(this); 
    } 

    onMessage(_message: any) { 

    } 
} 

bootstrap(App, [MyService]).catch(err => console.error(err)); 

回答

0

兩者都有rticles:Change detectionAngular immutability解釋了很多關於Angular 2如何檢測對象變化以及如何遍歷角2中的組件的樹以執行數據綁定......

在您的示例中,我認爲您的組件「我的應用程序「可以被認爲是」不可變的「,因此將其」變更檢測策略「更改爲OnPush可以解決您的問題。

你可以這樣寫:

@Component({ 
    selector: 'my-app', 
    changeDetection: ChangeDetectionStrategy.OnPush, 
    template : ` 
     <div> 
      <ul> 
       <li *ng-for="#item of m_items"> 
        {{item.getTitle()}} 
       </li> 
      </ul> 
     </div> 
    ` 
}) 

和增加進口來ChangeDetectionStrategy的「我的應用程序內」不會每次瀏覽器事件後計算的數據綁定之後,卻只有它的輸入變化的時候,所以不要。 ..