为什么我的值没有在init(Angular + Electron)上更新?

问题描述 投票:0回答:1

setting.component.ts

import { Component, OnInit } from '@angular/core';
import { ElectronService } from 'ngx-electron';

@Component({
  selector: 'app-setting',
  templateUrl: './setting.component.html',
  styleUrls: ['./setting.component.css']
})
export class SettingComponent implements OnInit {
  private primaryServer: string;
  private secondaryServer: string;

  constructor(
    private electron: ElectronService
  ) { }

  ngOnInit() {
    this.electron.ipcRenderer.send("asynchronous-message", {get: "settings"})
    this.electron.ipcRenderer.on("asynchronous-reply", (event, data) => {
      this.primaryServer = data.database.primary;
      this.secondaryServer = data.database.secondary;
    })
  }
}

setting.component.html

<p>{{primaryServer}}</p>
<p>{{secondaryServer}}</p>

页面加载时,我的“primaryServer”和“secondaryServer”值不会显示。但是,当我点击输入或随机按钮时,它会显示出来。如何让它们出现在init上?

angular electron
1个回答
2
投票
import { Component, OnInit, NgZone } from '@angular/core';
import { ElectronService } from 'ngx-electron';

@Component({
  selector: 'app-setting',
  templateUrl: './setting.component.html',
  styleUrls: ['./setting.component.css']
})
export class SettingComponent implements OnInit {
  private primaryServer: string;
  private secondaryServer: string;

  constructor(
    private electron: ElectronService,
    private zone: NgZone
  ) { }

  ngOnInit() {
    this.electron.ipcRenderer.send("asynchronous-message", {get: "settings"})
    this.electron.ipcRenderer.on("asynchronous-reply", (event, data) => {
      this.zone.run(()=>{
        this.primaryServer = data.database.primary;
        this.secondaryServer = data.database.secondary;
      })
    })
  }
}

这是我为正确更新所做的更改,如上所述

您的代码可能在Angulars区域之外运行,因此Angular无法识别它需要运行更改检测。您可以使用zone.run(()=> {您在此处更新模型的代码})来强制代码返回区域。如果这样可行,您可以进一步调查它在Angulars区域外运行的原因。 - Günter Zöchbauer

© www.soinside.com 2019 - 2024. All rights reserved.