Angular 7-动态在组件之间共享变量
创始人
2024-10-16 21:32:13
0

在Angular中,可以使用服务(service)来实现在组件之间共享变量。下面是一个示例解决方法:

  1. 创建一个共享服务(shared.service.ts):
import { Injectable } from '@angular/core';

@Injectable()
export class SharedService {
  sharedVariable: string;

  constructor() { }
}
  1. 在需要共享变量的组件中,注入共享服务并使用它:
import { Component } from '@angular/core';
import { SharedService } from './shared.service';

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

Component 1

Shared Variable: {{ sharedService.sharedVariable }}

`, }) export class Component1 { constructor(public sharedService: SharedService) { } }
  1. 在另一个组件中也注入共享服务并使用共享的变量:
import { Component } from '@angular/core';
import { SharedService } from './shared.service';

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

Component 2

Shared Variable: {{ sharedService.sharedVariable }}

`, }) export class Component2 { constructor(public sharedService: SharedService) { } }
  1. 在模块中提供共享服务:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { Component1 } from './component1.component';
import { Component2 } from './component2.component';
import { SharedService } from './shared.service';

@NgModule({
  imports: [BrowserModule],
  declarations: [AppComponent, Component1, Component2],
  providers: [SharedService],
  bootstrap: [AppComponent]
})
export class AppModule { }

这样,Component1和Component2中都可以使用sharedService.sharedVariable来共享变量的值。当一个组件修改了共享变量的值,另一个组件也会得到更新。

相关内容

热门资讯

一分钟揭秘!wepoker数据... 一分钟揭秘!wepoker数据分析,德普之星透视辅助软件激活码,细节方法(有挂技巧);德普之星透视辅...
记者揭秘!wepoker私人局... 记者揭秘!wepoker私人局辅助器怎么用,wepoker手机插件,2025新版技巧(有挂技巧);建...
记者发布!如何下载wepoke... 记者发布!如何下载wepoker安装包,微扑克微乐辅助,黑科技教程(有挂攻略)关于如何下载wepok...
揭秘关于!agpoker辅助,... 1、揭秘关于!agpoker辅助,hhpoker必备开挂,新2025教程(有挂透明)。2、hhpok...
重大发现!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...