2016-05-15 54 views
2

我試圖創建角2的應用程序,並在我的應用程序有一個身份驗證服務,我的HTML模板是財產以後這樣的:爲什麼* ng在角2中總是在使用函數時執行?

<header> 
    <div *ngIf="isLogin()"><a href="">profile</a></div> 
    <div *ngIf="!isLogin()"><a href="">register</a></div> 
    <div *ngIf="!isLogin()"><a href="">signin</a></div> 
    </header> 

**and this is my class :** 

@Component({ 
    selector: 'main-menu', 
    templateUrl: '/client/tmpl/menu.html', 
    directives: [ROUTER_DIRECTIVES] 
}) 
export class Menu extends Ext { 

    public items: any; 

    constructor(private _util: UtilService, private _user: UserService) { 
     super(); 


    } 

    public isLogin() { 

     console.log("test"); <==== my problem is here 
     return this._user.authorized(); 

    } 


} 

一直是我的職能在執行時(在我的身份驗證服務,我有另一個功能,他們也runing)!這是使用裏面的函數* ngif ?? !!! 我擔心我的資源,我想知道它的問題與否?

+1

你想要做什麼?顯然你的函數必須每次調用,因爲它在視圖上綁定了綁定,所以每次角度檢查isLogin中的任何變化。 –

+0

這就像setinterval或無限循環! –

+0

請你能改寫你的文章,這是不可理解的。 – Romain

回答

9

每次運行Angulars變更檢測時,它都會評估所有綁定,因此會調用您的函數來檢查視圖是否需要更新。

不鼓勵在綁定中使用函數。將值分配給組件類的屬性,並將其綁定到此屬性,或者使用observables和| async管道向Angular通知有關已更改的值。

另一種選擇是使用ChangeDetectionStrategy.OnPush,其中角度更改檢測僅在輸入值更改時運行。

+1

@AlirezaValizade,請參閱Günter關於此問題的其他答案:http://stackoverflow.com/questions/37024918/angular2- changedetection-or-observable/37025051#37025051 –

+0

我在我的項目中的很多地方都使用過ngIf函數。是否有任何頁面崩潰的風險,由於他們?我應該改變它們還是很好? – sunnyiitkgp

+0

如果他們沒有做任何實際的工作,只是返回一個簡單的值,他們並不太壞。使用裸露字段更改檢測效率仍然更高。如果您使用'OnPush',則更不會出現問題,因爲更改檢測不會經常運行。如果函數的計算量適中,則必須將其更改爲屬性綁定。 –

相關問題