Angular 6 - 使用Observable在兄弟组件之间触发事件
创始人
2024-10-16 02:30:12
0

在Angular 6中使用Observable在兄弟组件之间触发事件的解决方法可以分为以下几个步骤:

  1. 创建一个共享的服务,用于在兄弟组件之间共享数据和触发事件。可以使用Angular的@Injectable装饰器将服务标记为可注入的。
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable()
export class SharedService {
  private subject = new Subject();

  sendMessage(message: string) {
    this.subject.next({ text: message });
  }

  clearMessages() {
    this.subject.next();
  }

  getMessage() {
    return this.subject.asObservable();
  }
}
  1. 在发送事件的组件中,注入共享服务,并调用sendMessage方法来发送消息。
import { Component, OnInit } from '@angular/core';
import { SharedService } from './shared.service';

@Component({
  selector: 'app-sender',
  template: `
    
  `,
})
export class SenderComponent {
  constructor(private sharedService: SharedService) { }

  sendMessage() {
    this.sharedService.sendMessage('Hello from sender component!');
  }
}
  1. 在接收事件的组件中,注入共享服务,并调用getMessage方法来订阅消息。
import { Component, OnInit } from '@angular/core';
import { SharedService } from './shared.service';

@Component({
  selector: 'app-receiver',
  template: `
    
{{ message }}
`, }) export class ReceiverComponent implements OnInit { message: string; constructor(private sharedService: SharedService) { } ngOnInit() { this.sharedService.getMessage().subscribe(message => { this.message = message.text; }); } }

通过以上步骤,你可以在兄弟组件之间通过共享服务和Observable来触发事件和共享数据。当发送组件中的按钮被点击时,会发送一条消息到接收组件,并在接收组件中显示出来。

相关内容

热门资讯

第十分钟辅助!如何下载wpk透... 第十分钟辅助!如何下载wpk透视版,pokerworld软件,策略教程(有挂分享)如何下载wpk透视...
九分钟辅助!wepoker辅助... 九分钟辅助!wepoker辅助真的假的,cloudpoker作弊,手筋教程(证实有挂)1、每一步都需...
第十分钟辅助!wejoker辅... 第十分钟辅助!wejoker辅助器怎么卖,wepoker免费透视脚本,窍门教程(有挂方式)1、进入游...
十分钟辅助!wepoker-h... 十分钟辅助!wepoker-h5下载,pokernow辅助控制,绝活教程(有挂实锤)1、点击下载安装...
5分钟辅助!aapoker辅助... 5分钟辅助!aapoker辅助器怎么用,wepoker模拟器哪个好用,模板教程(有挂辅助)wepok...
八分钟辅助!wpk官网下载链接... 八分钟辅助!wpk官网下载链接,wpk透视怎么安装,教程书教程(有挂分享)该软件可以轻松地帮助玩家将...
9分钟辅助!wepoker怎么... 9分钟辅助!wepoker怎么买辅助,wepoker安装教程,课程教程(有挂方略)1、wepoker...
第七分钟辅助!hh poker... 第七分钟辅助!hh poker插件下载,wepoker科技辅助器,教程书教程(有挂教程)wepoke...
三分钟辅助!hhpoker脚本... 三分钟辅助!hhpoker脚本下载,hhpoker辅助器,举措教程(有挂教程)三分钟辅助!hhpok...
第8分钟辅助!hhpoker的... 第8分钟辅助!hhpoker的辅助是真的吗,wepoker祈福有用吗,讲义教程(有挂解密)1、第8分...