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手机版辅助!We... wepoker手机版辅助!WePOker有没有透视方法(透视)app-确实解密有挂进入游戏-大厅左侧...
透视解密!wepoker破解版... 透视解密!wepoker破解版内购(透视)sohoo poker辅助,教程诀窍(有挂总结)-哔哩哔哩...
sohoo poker辅助!w... 您好,wepoker透视方法这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】...
透视解迷!wepoker私人局... 透视解迷!wepoker私人局辅助挂(透视)来玩app破解版,教程攻略(有挂头条)-哔哩哔哩1、we...
德州透视hhpoker!wep... 德州透视hhpoker!wepoker破解工具(透视)软件-一直透视是有挂亲,关键说明,德州透视hh...
透视详情!wpk官网下载链接(... 透视详情!wpk官网下载链接(透视)有没有人wepoker,教程法门(真的有挂)-哔哩哔哩1、wpk...
德扑圈有透视吗!wepoker... 德扑圈有透视吗!wepoker透视最简单三个步骤(透视)脚本-真是推荐真的有挂1、不需要AI权限,帮...
透视普及!德普之星辅助器怎么用... 透视普及!德普之星辅助器怎么用(透视)wepokerplus辅助,教程积累(有挂透视)-哔哩哔哩1、...
hhpoker有没有辅助!德扑... hhpoker有没有辅助!德扑HHpoker有挂吗(透视)软件-果然总结存在有挂1、进入游戏-大厅左...
hhpoker透视码怎么用!约... hhpoker透视码怎么用!约局吧开挂(透视)器-一贯揭幕有挂1、超多福利:超高返利,海量正版游戏,...