Angular 創建 可觀察對象(Observable)


message.service.ts  

// 創建可觀察對象
import { Injectable } from '@angular/core';
import {Observable} from 'rxjs';
import { Subject } from 'rxjs';

@Injectable()
export class MessageService {
    private subject = new Subject<any>();

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

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

    getMessage(): Observable<any> {
        return this.subject.asObservable();
    }
}
home.component.ts

import { Component } from '@angular/core';
import { MessageService } from 'src/app/service/single.service'
 import { Subscription } from 'rxjs';

@Component({
    templateUrl: 'home.component.html'
})

export class HomeComponent OnDestroy
{
      subscription: Subscription;
    constructor(private messageService: MessageService) {
      // 創建觀察者
      this.subscription = this.messageService.getMessage()
              .subscribe(message => { console.log('message', message) });
      this.sendMessage() // 發短信
  }
    
    sendMessage(): void { // 發送消息
        this.messageService.sendMessage('Message from Home Component to App Component!');
    }

    clearMessage(): void { // 清除消息
        this.messageService.clearMessage();
    }

   ngOnDestroy() {
        // 關閉監聽
        this.subscription.unsubscribe();
    }

}    

 


免責聲明!

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



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