我有以下代码:app.html:<ion-menu [content]="content"> <ion-content [ngStyle]="{'background': 'linear-gradient(#'+menuColor1+', #'+menuColor2+')'}"> ... </ion-content></ion-menu><ion-nav #content [root]="rootPage" swipeBackEnabled="false"></ion-nav>app.components.ts:import { Component } from '@angular/core';import { Platform } from 'ionic-angular';import { StatusBar } from '@ionic-native/status-bar';import { SplashScreen } from '@ionic-native/splash-screen';import { TabsPage } from '../pages/tabs/tabs';import { GlobalsProvider } from '../providers/globals/globals';@Component({ templateUrl: 'app.html'})export class MyApp { rootPage: any = TabsPage; menuColor1: string = GlobalsProvider.MENU_COLOR_1; menuColor2: string = GlobalsProvider.MENU_COLOR_2; constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) { GlobalsProvider.MENU_COLOR_1 = "f00"; GlobalsProvider.MENU_COLOR_2 = "ff0"; console.log(GlobalsProvider.MENU_COLOR_1); // f00 console.log(this.menuColor1); // 000 (expected: f00) console.log(GlobalsProvider.MENU_COLOR_2); // ff0 console.log(this.menuColor2); // 000 (expected: ff0) }); platform.ready().then(() => { // Okay, so the platform is ready and our plugins are available. // Here you can do any higher level native things you might need. statusBar.styleDefault(); splashScreen.hide(); }); }}globals.ts:export const GlobalsProvider = { MENU_COLOR_1: "000", MENU_COLOR_2: "000",}我想在app.component.ts和globals.ts之间做两种方式的数据绑定,每次更改vars MENU_COLOR_1和MENU_COLOR_2时,也在menuColor1和menuColor2值中进行更新(我将更新和MENU_COLOR_1将来也来自另一个componenet,我希望MENU_COLOR_2和menuColor1收到这些更改)。有可能的? (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 对象是可变的,并通过引用传递。像string这样的原始类型没有变化,因此它们并没有像您希望的那样变化。因此,您应该做的是使用对象:menuColor1 = GlobalsProvider;menuColor2 = GlobalsProvider;ngOnInit() { GlobalsProvider.MENU_COLOR_1 = "f00"; GlobalsProvider.MENU_COLOR_2 = "ff0"; console.log(GlobalsProvider.MENU_COLOR_1); // f00 console.log(this.menuColor1.MENU_COLOR_1); console.log(GlobalsProvider.MENU_COLOR_2); // ff0 console.log(this.menuColor2.MENU_COLOR_2);}但是要非常小心,因为如上所述,对象是通过引用传递的,所以有时您可能不希望出现这种情况。 (adsbygoogle = window.adsbygoogle || []).push({});
10-07 14:56