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

来源:  2018-04-04 17:27:21    评论:0点击:

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<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 './message.service';

@Component({
    selector: 'exe-home',
    template: `
    <div>
        <h1>Home</h1>
        <button (click)="sendMessage()">Send Message</button>
        <button (click)="clearMessage()">Clear Message</button>
    </div>`
})

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






来源:https://blog.csdn.net/ChangerJJLee/article/details/78675290
为您推荐

友情链接 |九搜汽车网 |手机ok生活信息网|ok生活信息网|ok微生活
 Powered by www.360SDN.COM   京ICP备11022651号-4 © 2012-2016 版权