Angular中通过创建service来进行兄弟组件间通信

1. 创建公共服务

一般在公共文件内创建公共服务,命令:ng g s 路径\服务名称如: ng g s service\storage。得到 storage.service.ts,实现内容如下:

import { Injectable } from '@angular/core';
// 1. 引入BehaviorSubject
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class StorageService {
  constructor() {}
  // 2. 创建subject(自定义)
  subject: BehaviorSubject<any> = new BehaviorSubject<any>(0);
}

2. 在 app.module.ts 文件中引入公共 storage.service.ts 文件,并声明。

import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CpmoneComponent } from './cpmone/cpmone.component';
import { CpmtowComponent } from './cpmtow/cpmtow.component';
// 1.引入
import { StorageService } from './service/storage.service';

@NgModule({
  declarations: [AppComponent, CpmoneComponent, CpmtowComponent],
  imports: [BrowserModule, AppRoutingModule, FormsModule],
  // 2. 声明
  providers: [StorageService],
  bootstrap: [AppComponent],
})
export class AppModule {}

3. 在 A 组件

import { Component, OnInit } from '@angular/core';
// 1. 引入
import { StorageService } from '../service/storage.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-cpmone',
  templateUrl: './cpmone.component.html',
  styleUrls: ['./cpmone.component.less'],
})
export class CpmoneComponent implements OnInit {
  // 2. 注册
  constructor(public storageService: StorageService, private router: Router) {}

  ngOnInit(): void {}

  inputValue = '';

  public send(): void {
    this.router.navigate(['/tow']);
    // 3. 发布
    this.storageService.subject.next(this.inputValue);
  }
}

4. 在 B 组件

import { Component, OnInit } from '@angular/core';
// 1. 引入
import { Subscription } from 'rxjs';
import { StorageService } from '../service/storage.service';

@Component({
  selector: 'app-cpmtow',
  templateUrl: './cpmtow.component.html',
  styleUrls: ['./cpmtow.component.less'],
})
export class CpmtowComponent implements OnInit {
  data: any;
  isVisible = false;

  // 2. subscription
  subscription: Subscription; 

  constructor(public storageService: StorageService) {
    // 3. 订阅,并用 subscription 接收
    this.subscription = this.storageService.subject.subscribe((data) => {
      this.data = data;
      console.log('ok');
    });
    console.log('okk');
  }

  showData() {
    this.isVisible = true;
  }

  ngOnInit(): void {}

  ngOndestry(): void {
    // 4. 注销订阅
    this.subscription.unsubscribe();
  }
}

 

posted @ 2022-07-19 23:54  RHCHIK  阅读(299)  评论(0编辑  收藏  举报