angular service 進行組件通信


MessageService 代碼如下

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
  providedIn: 'root'
})
export class MessageService {
  private messageSource = new Subject<string>();
  message$ = this.messageSource.asObservable();
  messageAction(name: string) {
    this.messageSource.next(name);
  }
}

發送消息的組件 代碼如下

ts

import { Component} from '@angular/core';
import { MessageService } from '../service/message.service';
@Component({
  selector: 'app-send',
  templateUrl: './send.component.html',
  styleUrls: ['./send.component.css']
})
export class SendComponent {
  constructor(private messageService: MessageService) { }
  sendMessage(action: string) {
    this.messageService.messageAction(action);
  }

html

<input #action>
<button (click)="sendMessage(action.value)">action</button>

接收消息的組件

ts

import { Component, OnInit, OnDestroy } from '@angular/core';
import { MessageService } from './service/message.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
  action: string;
  sub: Subscription;
  ngOnInit(): void {
    this.messageService.message$.subscribe(action => this.action = action);
  }
  ngOnDestroy(): void {
    this.sub.unsubscribe(); //不要忘記取消訂閱
  }
  constructor(private messageService: MessageService) {
  }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM