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'

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

export class HomeComponent OnDestroy
{
    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();
    }

}    

猜你喜欢

转载自www.cnblogs.com/lvsk/p/12922914.html