Angular 7两个组件之间的数据共享
创始人
2024-10-17 02:30:40
0

在Angular 7中,可以使用服务(service)来实现两个组件之间的数据共享。以下是一个具体的解决方法,包含代码示例:

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

@Injectable()
export class SharedService {
  private data = new BehaviorSubject(''); // 初始值为空字符串
  currentData = this.data.asObservable();

  constructor() { }

  updateData(newData: string) {
    this.data.next(newData);
  }
}
  1. 在需要共享数据的组件A中,注入数据共享服务:
import { Component } from '@angular/core';
import { SharedService } from './shared.service';

@Component({
  selector: 'app-component-a',
  template: `
    
  `
})
export class ComponentA {
  data: string;

  constructor(private sharedService: SharedService) { }

  updateSharedData() {
    this.sharedService.updateData(this.data);
  }
}
  1. 在需要访问共享数据的组件B中,同样注入数据共享服务:
import { Component } from '@angular/core';
import { SharedService } from './shared.service';

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

Shared Data: {{ sharedData }}

` }) export class ComponentB { sharedData: string; constructor(private sharedService: SharedService) { this.sharedService.currentData.subscribe(data => { this.sharedData = data; }); } }

通过以上步骤,组件A可以更新数据并将其传递给数据共享服务,而组件B可以订阅数据共享服务以获取最新的共享数据。

请注意,在使用此方法时,需要将SharedService提供给应用的根模块(AppModule)中的providers数组:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { ComponentA } from './component-a.component';
import { ComponentB } from './component-b.component';
import { SharedService } from './shared.service';

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

这样,Angular就可以正确地注入共享服务并在组件A和组件B之间共享数据了。

相关内容

热门资讯

一起来探讨!wepoker好友... 此外,数据分析德州(wepoker好友房开挂)辅助神器app还具备辅助透视行为开挂功能,通过对客户w...
科技介绍!pokemmo脚本辅... 科技介绍!pokemmo脚本辅助器,wepoker数据分析工具,微扑克教程(有挂教程)准备好在wep...
重磅来袭!aapoker透视脚... 重磅来袭!aapoker透视脚本下载,wepoker私人定制透视,介绍教程(有挂方法)是一款可以让一...
发现玩家!aapoker怎么开... 《发现玩家!aapoker怎么开辅助器,sohoo poker辅助器,玩家教程(有挂技巧)》 aap...
技巧知识分享!wepoker辅... 技巧知识分享!wepoker辅助插件功能,hhpoker辅助挂,新版2025教程(有挂透明)关于we...
总算清楚!wepoker可以透... 总算清楚!wepoker可以透视码,we-poker辅助软件教程,必备教程(有挂技巧)1、点击下载安...
重大通报!wepoker底牌透... 1、重大通报!wepoker底牌透视,拱趴大菠萝有挂吗,必赢方法(有挂软件);详细教程。2、拱趴大菠...
推荐十款!wepoker国外版... 此外,数据分析德州(wepoker怎么挂底牌)辅助神器app还具备辅助透视行为开挂功能,通过对客户w...
揭秘!wepoker透视脚本是... 揭秘!wepoker透视脚本是什么,werplan怎么作弊,透明挂教程(有挂透明)1、点击下载安装,...
今日焦点!智星菠萝可以辅助吗,... 今日焦点!智星菠萝可以辅助吗,wepoker私局辅助,普及教程(有挂透视)1、点击下载安装,微扑克w...