2016-06-28 67 views
0

當我運行應用程序時,控制檯會顯示我擁有ngOnInit的所有日誌,但應用程序只生成一個框架視圖,而不顯示來自l18n的組件和文本的變量。 ngOnInit或者不應該像它應該那樣工作,因爲我必須在構造函數中調用它。模板中的Angular2 Init變量。

當我第二次點擊一個組件的鏈接時,這些問題就消失了,然後所有的東西都按照它的樣子加載。這發生在應用程序中的所有組件以及構建在angular2 starter gulp上的所有應用程序中。

爲什麼只有第二次點擊加載變量來查看和調用ngOnInit(當它在構造函數中調用時)?

export class SettingsDevicesComponent implements OnInit { 

**variables** 

@Component({ 
    selector: 'as-settings-devices', 
    templateUrl: 'app/settings-devices/settings-devices.component.html', 
    changeDetection: ChangeDetectionStrategy.OnPush, 
    styleUrls: ['app/settings-devices/settings-devices.component.css'], 
    providers: [Communication], 
    pipes: [TranslatePipe], 
    directives: [REACTIVE_FORM_DIRECTIVES, NgClass, NgStyle, CORE_DIRECTIVES,ROUTER_DIRECTIVES] 
}) 

constructor(private _cm: Communication, 
      private _cdRef: ChangeDetectorRef, 
      private _router: Router, 
      private _sanitizer: DomSanitizationService, 
      @Inject(ElementRef) elementRef: ElementRef 
      ) { 
       this.elementRef = elementRef; 
       this.ngOnInit(); 
       this.fileUpload = new FormGroup({ 
        color: this.color 
       }); 
       this.fileName = new FormGroup({ 
        fileNameInput: this.fileNameInput 
       }); 
       this.settingsName = new FormGroup({ 
        settingsNameInput: this.settingsNameInput 
       }); 
      } 

ngOnInit() { 
    this.getDeviceData(); 
    this.getZoneData(); 
} 
} 
+0

在瀏覽器控制檯中是否有任何錯誤?這聽起來像是一個時間問題。 getDeviceData()和getZoneData()是做什麼的?從構造函數或'ngOnInit()'調用它們應該沒有多大區別。 –

+0

如果您從構造函數中調用'ngOnInit()',則會執行this.getDeviceData(); this.getZoneData();'兩次。如果你依賴它在那裏執行,將代碼移動到構造函數會更好,而不是從構造函數中調用'ngOnInit()'。 –

+0

getDeviceData(),getZoneData()是http服務 – Emerceen

回答

1

問題是changeDetection:ChangeDetectionStrategy.OnPush的主要成分 'app.component.ts'

這引起了一個問題:

@Component({ 
    selector: 'as-main-app', 
    templateUrl: 'app/app.html', 
    changeDetection: ChangeDetectionStrategy.OnPush, 
    directives: [ROUTER_DIRECTIVES] 
}) 

消除一切之後是確定的:

@Component({ 
    selector: 'as-main-app', 
    templateUrl: 'app/app.html', 
    directives: [ROUTER_DIRECTIVES] 
})