Angular 2/5 - Communicating Between Components with Observable & Subject

12 篇文章 0 订阅
5 篇文章 0 订阅

angular模块间通信(component间或者懒加载的modlue间)可以采用 Observable & Subject方式,也可采用EventEmitter方式,都是将他们封装成一个 @Injectable() 服务,但是不推荐用EventEmitter方式,因为将来官方不保证对EventEmitter做修改的后的兼容性

------------------------------------------------------------------------------------------------------------------------------------

http://jasonwatmore.com/post/2016/12/01/angular-2-communicating-between-components-with-observable-subject


Nov 29 2017 - Updated to Angular 5.0.3

This is a quick post to show an example of something that got me stuck for a little while - how to communicate between components in Angular 2/5.

The solution is to use an Observable and a Subject (which is a type of observable), I won't go too much into the details about how observables work here, but in a nutshell there are two methods that we're interested in: Observable.subscribe() and Subject.next().

Observable.subscribe()

The observable subscribe method is used to subscribe to messages that are sent to an observable.

Subject.next()

The subject next method is used to send messages to an observable which are then sent to all subscribers of that observable.


Example of Component Communication in Angular 2/5

Here's a simple example showing a home component communicating with the root app component via a message service using observables.

The code is also available on GitHub at https://github.com/cornflourblue/angular2-communicating-between-components

(See on Plunker at http://plnkr.co/edit/FHIPt1?p=preview)

Update History:

  • 29 Nov 2017 - Updated to Angular 5.0.3
  • 23 May 2017 - Updated to Angular 4.1.3
  • 01 Dec 2016 - Built with Angular 2.2.1


Running the Angular 2/5 Component Communication Example Locally

  1. Install NodeJS (> v4) and NPM (> v3) from https://nodejs.org/en/download/, you can check the versions you have installed by running node -v and npm -v from the command line.
     
  2. Download the project source code from https://github.com/cornflourblue/angular2-communicating-between-components
     
  3. Install all required npm packages by running npm install from the command line in the project root folder (where the package.json is located).
     
  4. Start the application by running npm start from the command line in the project root folder.


Angular 2/5 Message Service

The message service enables subscribing to messages and sending messages from any component in the application

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { Injectable } from  '@angular/core' ;
import { Observable } from  'rxjs' ;
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();
     }
}


Angular 2/5 App Component that Receives Messages

The app component uses the message service to subscribe to new messages and make them available to the app component template via the message property.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import { Component, OnDestroy } from  '@angular/core' ;
import { Subscription } from  'rxjs/Subscription' ;
 
import { MessageService } from  './_services/index' ;
 
@Component({
     moduleId: module.id,
     selector:  'app' ,
     templateUrl:  'app.component.html'
})
 
export class AppComponent implements OnDestroy {
     message: any;
     subscription: Subscription;
 
     constructor(private messageService: MessageService) {
         // subscribe to home component messages
         this .subscription =  this .messageService.getMessage().subscribe(message => {  this .message = message; });
     }
 
     ngOnDestroy() {
         // unsubscribe to ensure no memory leaks
         this .subscription.unsubscribe();
     }
}


Angular 2/5 Home Component that Sends Messages

The home component uses the message service to send messages to the app component.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import { Component } from  '@angular/core' ;
 
import { MessageService } from  '../_services/index' ;
 
@Component({
     moduleId: module.id,
     templateUrl:  'home.component.html'
})
 
export class HomeComponent {
     constructor(private messageService: MessageService) {}
     
     sendMessage(): void {
         // send message to subscribers via observable subject
         this .messageService.sendMessage( 'Message from Home Component to App Component!' );
     }
 
     clearMessage(): void {
         // clear message
         this .messageService.clearMessage();
     }
}


Recommended Books on Angular 2/5


Web Development Sydney

Feel free to drop me a line if you're looking for an Angular 2/5 developer or web developer in Sydney Australia, I also provide remote contracting services for clients outside Sydney.

------------------------------------------------------------------------------------------------------------------------------------


// Message service

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

@Injectable()
export class EmitDateService {

  dateEventer: EventEmitter<string> = new EventEmitter();
  constructor() { }
}


// header.component.ts 比如此组件的时间改变时,发射出时间值,其他所有组件订阅后,即可自动收到改变后的日期值

    constructor(private dateService: EmitDateService) {}

    public onDateChanged(event: IMyDateModel): void {
        this.dateService.dateEventer.emit(date);
    }


// 其他任何组件,用以下方式订阅

this._subscription = this.dateService.dateEventer.subscribe(date => {
        // date
});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值