【问题标题】:Angular2 Init variables in template.模板中的 Angular2 初始化变量。
【发布时间】:2016-06-28 07:11:57
【问题描述】:

当我运行应用程序时,控制台会显示我拥有 ngOnInit 的所有日志,但应用程序只生成一个框架视图,而不显示组件的变量和来自 l18n 的文本。 ngOnInit 或不能正常工作,因为我必须在构造函数中被调用。

当我第二次单击组件的链接时,这些问题就会消失,然后一切都按原样加载。这发生在应用程序中的所有组件以及基于 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();
}
}

【问题讨论】:

  • 您是否在浏览器控制台中收到任何错误。这听起来像是一个时间问题。 getDeviceData()getZoneData() 在做什么?从构造函数或ngOnInit() 调用它们应该没有太大区别。
  • 如果你从你的构造函数中调用ngOnInit()this.getDeviceData();this.getZoneData();会被执行两次。如果你依赖于它在那里执行,最好将这段代码移动到构造函数,而不是从构造函数调用ngOnInit()
  • getDeviceData(), getZoneData() 是http服务
  • 那么无论你在哪里调用它们都无关紧要,它们是异步执行的,并且无法保证响应何时到达。在构造函数执行时它肯定不会到达。
  • 我也有没有任何站点 http 的组件,并且在第一次点击后发生第二次点击后视图不变,跳转变量

标签: typescript angular


【解决方案1】:

问题是 changeDetection: ChangeDetectionStrategy.OnPush in main component '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]
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-20
    相关资源
    最近更新 更多