【Angular】非父子组件通信(使用rxjs+service)

组件间共享一个service服务,那么组件之间就可以通过service实现通信。

本博客使用rxjs中的subject来实现。文档:主体 - RxJS 中文版

1.创建service服务文件并引入subject

//DataService.service.ts
import {
    
     Injectable } from '@angular/core';
import {
    
     Subject} from 'rxjs';

@Injectable({
    
    
  providedIn: 'root',
})
export class DataService {
    
    
  subject: Subject<any> = new Subject<any>();

  constructor() {
    
    }
}

2.在app.module.ts中引入此service

providers: [DataService]

3.要发布数据的组件中

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

@Component({
    
    
  selector: 'app-a',
  templateUrl: './a.component.html',
})
export class AComponent {
    
    
  // 依赖注入
  constructor(public dataService: DataService) {
    
    }

  data: string = '';

  // 发布数据
  // 可以在这里console.log('组件A发送数据给组件B')
  send(): void {
    
    
    this.dataService.subject.next(data);
  }
}

4.接收数据的组件中

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

@Component({
    
    
  selector: 'app-b',
  templateUrl: './b.component.html',
})
export class BComponent {
    
    
  data: any;
  
  subscription: Subscription;

  constructor(public dataService: DataService) {
    
    
    this.subscription = this.dataService.subject.subscribe((data) => {
    
    
      // 对接收的数据操作
      this.data = data;
    });
  }

  ngOndestry(): void {
    
    
    // 销毁时取消订阅,防止内存泄漏
    this.subscription.unsubscribe();
  }
}

其他

也可以使用Subject的变体,如BehaviorSubject等。BehaviorSubject有初始值且会立即发送。 如果没有这个需要不建议使用。

参考:
玩转Angular系列:组件间各种通信方式详解 - 掘金 (juejin.cn)

猜你喜欢

转载自blog.csdn.net/karshey/article/details/134123854