我知道ngOnInit
和constructor
都能在页面初始化的时候执行,constructor
比ngOnInit
快,并且看到官网说尽量将复杂的内容放在ngOnInit
里,我也一直是这么做的。
然而最近遇到了一个问题,跳路由之后,页面只执行constructor
没有执行ngOnInit
,当我再次点击路由或者输入页面中的Input框时,才执行ngOnInit
。这导致了一个问题,跳路由时,我的页面加载不完全。
然后又滚去看官网,有这样一句话:Remember also that a directive's data-bound input properties are not set until after construction. That's a problem if we need to initialize the directive based on those properties. They'll have been set when our ngOninit runs.
中文翻译:另外还要记住,在指令的 构造函数完成之前 ,那些被绑定的输入属性还都没有值。 如果我们需要基于这些属性的值来初始化这个指令,这种情况就会出问题。 而当 ngOnInit 执行的时候,这些属性都已经被正确的赋值过了。
我表示没有看懂,另外看到说ngOnInit
会在第一次执行ngOnChanges
之后执行,那么我遇到的这个问题是因为我没有触发ngOnChanges
吗?
求大神解答。
以下是我的代码:
import {Component,OnInit,OnDestroy} from '@angular/core'; import {Router} from '@angular/router'; import {Http} from '@angular/http'; import {SettingService,LocalHostParams} from '../../services/setting.service'; import {Pagination} from '../pagination-modal/pagination'; @Component({ selector: 'setting-network', template: require('./setting-network.html'), styles: [require('./setting.css').toString()], directives: [Pagination] }) export class SettingNetwork implements OnInit,OnDestroy { private service:SettingService; private local_host_params:LocalHostParams; constructor(private http:Http, private _router:Router) { this.service = new SettingService(http); console.log('constructor') } ngOnInit() { console.log('ngOnInit') this.getLocalHostParams(); } getLocalHostParams() { this.service.getLocalHost().subscribe(data=> { var results = data.json(); this.local_host_params = { 'subnet_mask': results.subnet_mask, 'default_gateway': results.default_gateway, 'ip_address': results.ip_address, 'dns_server': results.dns_server, }; console.log(this.local_host_params) }); } ngOnDestroy() { //还没写 } }
html:
我遇到的情况和你的一样,最后发现是没有引入一个模块导致的
import 'core-js/es6';
楼主可以试一下,我的已经解决
用的是"core-js": "^2.4.1"