2016-06-28 48 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] 
})