Angular 5 - 从另一个组件中更改变量
创始人
2024-10-15 20:31:25
0

要从另一个组件中更改变量,你可以使用Angular中的服务(service)来共享数据。

首先,创建一个名为data.service.ts的新服务文件,并在其中定义一个变量和两个方法。

import { Injectable } from '@angular/core';

@Injectable()
export class DataService {
  private myVariable: string;

  constructor() {
    this.myVariable = 'Initial value';
  }

  getVariable(): string {
    return this.myVariable;
  }

  setVariable(newValue: string): void {
    this.myVariable = newValue;
  }
}

接下来,在要更改变量的组件中,将DataService注入到构造函数中,并使用它来获取和设置变量的值。

import { Component } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'app-component1',
  template: `
    

Variable value: {{ variable }}

`, }) export class Component1 { variable: string; constructor(private dataService: DataService) { this.variable = dataService.getVariable(); } changeVariable(): void { this.dataService.setVariable('New value'); this.variable = this.dataService.getVariable(); } }

最后,在另一个组件中,也将DataService注入到构造函数中,并使用它来获取变量的值。

import { Component } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'app-component2',
  template: `
    

Variable value: {{ variable }}

`, }) export class Component2 { variable: string; constructor(private dataService: DataService) { this.variable = dataService.getVariable(); } }

现在,当在Component1组件中点击按钮更改变量的值时,Component2组件中显示的变量值也会更新。这是因为它们使用了同一个DataService实例来共享数据。

相关内容

热门资讯

重大发现!aapoker破解侠... 重大发现!aapoker破解侠是真的吗,cloudpoker外挂,大神讲解(有挂神器)是由北京得aa...
必看攻略!wepoker怎么下... 必看攻略!wepoker怎么下载游戏,wepoker透视脚本免费下载,详细教程(有挂技巧);致您一封...
发现一款!德州局透视脚本,HH... 发现一款!德州局透视脚本,HH平台挂,扑克教程(有挂技巧)1、很好的工具软件,可以解锁游戏的ai质量...
推荐十款!aapoker真的假... 推荐十款!aapoker真的假的,aapoker透视脚本下载,wpk教程(有挂攻略)是一款可以让一直...
一起来讨论!wepoker有辅... 1、一起来讨论!wepoker有辅助功能吗,wepoker数据分析工具,规律教程(有挂方法)2、进入...
总算了解!wepoker公共底... 1、总算了解!wepoker公共底牌,aapoker发牌逻辑,教你教程(有挂攻略)。2、aapoke...
今日头条!wepoker挂,h... 今日头条!wepoker挂,hhpoker底牌透视脚本,可靠技巧(有挂技巧);亲真的是有正版授权,小...
1.9分钟了解!wepoker... 1.9分钟了解!wepoker破解器激活码,aapoker怎么开辅助器,大神讲解(有挂神器)科技教程...
我来教大家!wepoker游戏... 我来教大家!wepoker游戏的安装教程,德普之星透视软件免费入口官网,攻略教程(有挂神器)关于德普...
一分钟秒懂!pokemmo辅助... 一分钟秒懂!pokemmo辅助器手机版下载,智星德州插件怎么下载,2025新版(有挂技巧);人气非常...