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();
    }

}    

 

posted @ 2020-05-20 12:37  秦笑  阅读(1262)  评论(0)    收藏  举报