兄弟组件通信

  • 如何实现AngularJS2中不同组件间的通信?

    在AngularJS 2中,不同组件间的通信可以通过服务(Service)来实现。以下是一个简单的示例代码:,,``typescript,// shared.service.ts,import { Injectable } from '@angular/core';,import { BehaviorSubject } from 'rxjs';,,@Injectable({, providedIn: 'root',}),export class SharedService {, private messageSource = new BehaviorSubject('default message');, currentMessage = this.messageSource.asObservable();,, constructor() { },, changeMessage(message: string) {, this.messageSource.next(message);, },},,// component1.component.ts,import { Component, OnInit } from '@angular/core';,import { SharedService } from './shared.service';,,@Component({, selector: 'app-component1',, template: {{message}},}),export class Component1Component implements OnInit {, message: string;,, constructor(private sharedService: SharedService) { },, ngOnInit() {, this.sharedService.currentMessage.subscribe(message =˃ this.message = message);, },},,// component2.component.ts,import { Component } from '@angular/core';,import { SharedService } from './shared.service';,,@Component({, selector: 'app-component2',, template: Send Message,}),export class Component2Component {, message: string = 'Hello from Component 2';,, constructor(private sharedService: SharedService) { },, newMessage() {, this.sharedService.changeMessage(this.message);, },},`,,在这个例子中,我们创建了一个共享服务SharedService,它使用BehaviorSubject来存储和传递消息。Component1Component订阅了这个服务以接收消息,而Component2Component`通过点击按钮发送新的消息。

    2025-01-13
    03
免备案 高防CDN 无视CC/DDOS攻击 限时秒杀,10元即可体验  (专业解决各类攻击)>>点击进入