(一)Angular5 高级教程--基于 RxJS Subject的组件间通信

message.service.ts

import { Injectable } from '@angular/core';
import {Observable} from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';

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

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

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

    getMessage(): Observable {
        return this.subject.asObservable();
    }
}

home.component.ts

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

@Component({
    selector: 'exe-home',
    template: `
    

Home

` }) export class HomeComponent { constructor(private messageService: MessageService) {} sendMessage(): void { this.messageService.sendMessage('Message from Home Component to App Component!'); } clearMessage(): void { this.messageService.clearMessage(); } }

app.component.ts

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

@Component({
    selector: 'my-app',
    template: `
    <div>
       <div *ngIf="message">{{message.text}}div>
       
    div>
    `
})

export class AppComponent implements OnDestroy {
    message: any;
    subscription: Subscription;

    constructor(private messageService: MessageService) {
        this.subscription = this.messageService
                                  .getMessage().subscribe( message => { 
                                      this.message = message; 
                                 });
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}

你可能感兴趣的:(全栈攻城狮,Web前端,Angular征途)