Вы находитесь на странице: 1из 10

2/13/2019 Angular 7 - Communicating Between Components with Observable & Subject | Jason Watmore's Blog

FEBRUARY 07 2019

Angular 7 - Communicating Between  Sponsored by

Components with Observable & Subject


Built with Angular 7.2.3 and RxJS 6.4.0

(//srv.carbonads.n
Other versions available: et/ads/click/x/GT
ND42QMCTYDVK
React + RxJS - Communicating Between Components with Observable & Subject
7MF6A4YKQMCE
(/post/2019/02/13/react-rxjs-communicating-between-components-with-observable-
AIL53WCYSI6Z3JC
subject)
WBDL537CVSIKK
Angular 6 - Communicating Between Components with Observable & Subject
QKC6BIPK3ECKSI
(/post/2018/06/25/angular-6-communicating-between-components-with-
KK3EHJNCLSIZ?
observable-subject) segment=placem
Angular 2/5 - Communicating Between Components with Observableent:jasonwatmore
& Subject
(/post/2016/12/01/angular-2-communicating-between-components-with-observable-
;)
subject)
The new generation
of project
management tools is
This is a quick tutorial to show how you can communicate between components in Angular 7
here and it’s visual.
and RxJS. The tutorial example uses Webpack 4 for compiling + bundling and is styled with
(//srv.carbonads.net/
ads/click/x/GTND42
bootstrap 4. QMCTYDVK7MF6A4Y
KQMCEAIL53WCYSI6
Z3JCWBDL537CVSIK
The way to communicate between components is to use an Observable and a Subject (which
KQKC6BIPK3ECKSIK
K3EHJNCLSIZ?
is a type of observable), I won't go too much into the details about how observables work
segment=placement:
here since it's a big subject, but in a nutshell there are two methods that we're interested in:
jasonwatmore;)

Observable.subscribe() and Subject.next() . ads via Carbon


(http://carbonads.ne
t/?

Observable.subscribe()
utm_source=jasonw
atmore&utm_mediu
m=ad_via_link&utm
The observable subscribe method is used by angular components to subscribe to messages
_campaign=in_unit&
utm_term=carbon)
that are sent to an observable.
Supporter devv.jobs skills vs tech-stack matching 🤔anonymous&&free 😲 community contributed 😍
(https://codefund.app/impressions/d1c4bd9f-6f6f-40bd-97fb-a9d12e229b06/click?campaign_id=156) ethical ad by CodeFund

Subject.next() (https://codefund.app/?ref=d1c4bd9f-6f6f-40bd-97fb-a9d12e229b06)

http://jasonwatmore.com/post/2019/02/07/angular-7-communicating-between-components-with-observable-subject 1/10
2/13/2019 Angular 7 - Communicating Between Components with Observable & Subject | Jason Watmore's Blog

The subject next method is used to send messages to an observable which are then sent to
all angular components that are subscribers (a.k.a. observers) of that observable.

Sponsored by 
Angular 7 Component Communication Tutorial
Example
Here's a simple example showing communication between the home component and the
root app component via a message service using observables.
(//srv.carbonads.n
et/ads/click/x/GT
ND42QMCTYDVK
The tutorial code is available on GitHub at https://github.com/cornflourblue/angular-7-
7MF6A4YKQMCE
communicating-between-components (https://github.com/cornflourblue/angular-7-
AIL53WCYSI6Z3JC
communicating-between-components) WBDL537CVSIKK
QKC6BIPK3ECKSI
KK3EHJNCLSIZ?
segment=placem
ent:jasonwatmore
;)

The new generation


of project
management tools is
here and it’s visual.
(//srv.carbonads.net/
ads/click/x/GTND42
QMCTYDVK7MF6A4Y
KQMCEAIL53WCYSI6
Z3JCWBDL537CVSIK
KQKC6BIPK3ECKSIK
K3EHJNCLSIZ?
segment=placement:
jasonwatmore;)

ads via Carbon


(http://carbonads.ne
t/?
utm_source=jasonw
atmore&utm_mediu
m=ad_via_link&utm
_campaign=in_unit&
utm_term=carbon)

Supporter devv.jobs skills vs tech-stack matching 🤔anonymous&&free 😲 community contributed 😍


(https://codefund.app/impressions/d1c4bd9f-6f6f-40bd-97fb-a9d12e229b06/click?campaign_id=156) ethical ad by CodeFund
(https://codefund.app/?ref=d1c4bd9f-6f6f-40bd-97fb-a9d12e229b06)

http://jasonwatmore.com/post/2019/02/07/angular-7-communicating-between-components-with-observable-subject 2/10
2/13/2019 Angular 7 - Communicating Between Components with Observable & Subject | Jason Watmore's Blog

    https://angular-7-communication-between-components.stackblitz.io

Angular 7 Component Commun


 Sponsored by

Send Message Clear Messages

(//srv.carbonads.n
et/ads/click/x/GT
ND42QMCTYDVK
Angular 7 - Communicating Between Components with Observable
7MF6A4YKQMCE
AIL53WCYSI6Z3JC
J W WBDL537CVSIKK
Console 1 
QKC6BIPK3ECKSI
KK3EHJNCLSIZ?
segment=placem
ent:jasonwatmore
;)

The new generation


angular-7-communication-between-components Editor Preview Both
Edit on StackBlitz
of project
management tools is
(See on StackBlitz at https://stackblitz.com/edit/angular-7-communication-between-components here and it’s visual.
(//srv.carbonads.net/
(https://stackblitz.com/edit/angular-7-communication-between-components)) ads/click/x/GTND42
QMCTYDVK7MF6A4Y
KQMCEAIL53WCYSI6
Z3JCWBDL537CVSIK
KQKC6BIPK3ECKSIK

Running the Angular 7 Component K3EHJNCLSIZ?


segment=placement:
Communication Example Locally jasonwatmore;)

ads via Carbon


1. Install NodeJS and NPM from https://nodejs.org/en/download/ (http://carbonads.ne
(https://nodejs.org/en/download/). t/?
2. Download or clone the tutorial project code utm_source=jasonw
atmore&utm_mediu
from https://github.com/cornflourblue/angular-7-communicating-between- m=ad_via_link&utm
components (https://github.com/cornflourblue/angular-7-communicating-between- _campaign=in_unit&
components) utm_term=carbon)

3. Install all required


Supporter npm
devv.jobs packages
skills by
vs tech-stack running
matching npm install from
🤔anonymous&&free the command
😲 community contributed 😍line in the
project root folder (where the package.json is located).
(https://codefund.app/impressions/d1c4bd9f-6f6f-40bd-97fb-a9d12e229b06/click?campaign_id=156) ethical ad by CodeFund
(https://codefund.app/?ref=d1c4bd9f-6f6f-40bd-97fb-a9d12e229b06)

http://jasonwatmore.com/post/2019/02/07/angular-7-communicating-between-components-with-observable-subject 3/10
2/13/2019 Angular 7 - Communicating Between Components with Observable & Subject | Jason Watmore's Blog

4. Start the application by running npm start from the command line in the project root
folder.

Angular 7 Message Service Sponsored by 

With the message service you can subscribe to new messages in any component with
getMessage() method, send messages from any component with the sendMessage(message:

string) method, and clear messages from any component with the clearMessages() method.
(//srv.carbonads.n
et/ads/click/x/GT
The clearMessages() method actually just sends an empty message by calling
ND42QMCTYDVK
this.subject.next() without any arguments, the logic to clear the messages when an empty
7MF6A4YKQMCE
message is received is in the app component below. AIL53WCYSI6Z3JC
WBDL537CVSIKK
QKC6BIPK3ECKSI
KK3EHJNCLSIZ?
import { Injectable } from '@angular/core';
segment=placem
import { Observable, Subject } from 'rxjs';
ent:jasonwatmore
@Injectable({ providedIn: 'root' }) ;)
export class MessageService { The new generation
private subject = new Subject<any>(); of project
management tools is
sendMessage(message: string) { here and it’s visual.
this.subject.next({ text: message }); (//srv.carbonads.net/
ads/click/x/GTND42
}
QMCTYDVK7MF6A4Y
KQMCEAIL53WCYSI6
clearMessages() {
Z3JCWBDL537CVSIK
this.subject.next(); KQKC6BIPK3ECKSIK
} K3EHJNCLSIZ?
segment=placement:
getMessage(): Observable<any> { jasonwatmore;)
return this.subject.asObservable(); ads via Carbon
} (http://carbonads.ne
} t/?
utm_source=jasonw
atmore&utm_mediu
m=ad_via_link&utm
_campaign=in_unit&

Angular 7 App Component that Receives


Supporter devv.jobs skills vs tech-stack matching 🤔anonymous&&free 😲 community contributed 😍
utm_term=carbon)

Messages
(https://codefund.app/impressions/d1c4bd9f-6f6f-40bd-97fb-a9d12e229b06/click?campaign_id=156) ethical ad by CodeFund
(https://codefund.app/?ref=d1c4bd9f-6f6f-40bd-97fb-a9d12e229b06)

http://jasonwatmore.com/post/2019/02/07/angular-7-communicating-between-components-with-observable-subject 4/10
2/13/2019 Angular 7 - Communicating Between Components with Observable & Subject | Jason Watmore's Blog

The app component uses the message service to subscribe to new messages and push them
into the messages array which is displayed in the app component template. If an empty
message is received then the messages array is cleared which automatically removes the
messages from the UI.
Sponsored by 

import { Component, OnDestroy } from '@angular/core';


import { Subscription } from 'rxjs';

import { MessageService } from './_services/index';


(//srv.carbonads.n
@Component({ et/ads/click/x/GT
selector: 'app', ND42QMCTYDVK
templateUrl: 'app.component.html'
7MF6A4YKQMCE
})
AIL53WCYSI6Z3JC
WBDL537CVSIKK
export class AppComponent implements OnDestroy {
QKC6BIPK3ECKSI
messages: any[] = [];
KK3EHJNCLSIZ?
subscription: Subscription;
segment=placem
constructor(private messageService: MessageService) { ent:jasonwatmore
// subscribe to home component messages ;)
this.subscription = this.messageService.getMessage().subscribe(message => The
{ new generation
if (message) { of project
this.messages.push(message); management tools is
} else { here and it’s visual.
// clear messages when empty message received (//srv.carbonads.net/
ads/click/x/GTND42
this.messages = [];
QMCTYDVK7MF6A4Y
}
KQMCEAIL53WCYSI6
});
Z3JCWBDL537CVSIK
} KQKC6BIPK3ECKSIK
K3EHJNCLSIZ?
ngOnDestroy() { segment=placement:
// unsubscribe to ensure no memory leaks jasonwatmore;)
this.subscription.unsubscribe(); ads via Carbon
} (http://carbonads.ne
} t/?
utm_source=jasonw
atmore&utm_mediu
m=ad_via_link&utm
_campaign=in_unit&

Angular 7 Home Component that Sends


Supporter devv.jobs skills vs tech-stack matching 🤔anonymous&&free 😲 community contributed 😍
utm_term=carbon)

Messages
(https://codefund.app/impressions/d1c4bd9f-6f6f-40bd-97fb-a9d12e229b06/click?campaign_id=156) ethical ad by CodeFund
(https://codefund.app/?ref=d1c4bd9f-6f6f-40bd-97fb-a9d12e229b06)

http://jasonwatmore.com/post/2019/02/07/angular-7-communicating-between-components-with-observable-subject 5/10
2/13/2019 Angular 7 - Communicating Between Components with Observable & Subject | Jason Watmore's Blog

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

import { Component } from '@angular/core';

import { MessageService } from '../_services/index'; Sponsored by 

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


export class HomeComponent {
constructor(private messageService: MessageService) { }

sendMessage(): void { (//srv.carbonads.n


// send message to subscribers via observable subject et/ads/click/x/GT
ND42QMCTYDVK
this.messageService.sendMessage('Message from Home Component to App Component!');
} 7MF6A4YKQMCE
AIL53WCYSI6Z3JC
clearMessages(): void { WBDL537CVSIKK
// clear messages QKC6BIPK3ECKSI
this.messageService.clearMessages(); KK3EHJNCLSIZ?
} segment=placem
}
ent:jasonwatmore
;)

The new generation


of project

Web Development Sydney management tools is


here and it’s visual.
(//srv.carbonads.net/
Feel free to contact me (/contact) if you're looking for an Angular 7 developer in Sydney, I
ads/click/x/GTND42
also provide remote contracting services for clients outside Sydney. QMCTYDVK7MF6A4Y
KQMCEAIL53WCYSI6
Z3JCWBDL537CVSIK
KQKC6BIPK3ECKSIK
K3EHJNCLSIZ?
Tags: Angular 7 (/posts/tag/angular-7), Angular 2 (/posts/tag/angular-2), RxJS (/posts/tag/rxjs),
segment=placement:
TypeScript (/posts/tag/typescript) jasonwatmore;)

ads via Carbon


(http://carbonads.ne
Share: t/?
utm_source=jasonw
atmore&utm_mediu
m=ad_via_link&utm
_campaign=in_unit&

MoreSupporter
Angular 7 Posts
devv.jobs skills vs tech-stack matching 🤔anonymous&&free 😲 community contributed 😍
utm_term=carbon)

(https://codefund.app/impressions/d1c4bd9f-6f6f-40bd-97fb-a9d12e229b06/click?campaign_id=156)
Angular 7 - Role Based Authorization Tutorial with Example (/post/2018/11/22/angular- ethical ad by CodeFund
(https://codefund.app/?ref=d1c4bd9f-6f6f-40bd-97fb-a9d12e229b06)
7-role-based-authorization-tutorial-with-example)

http://jasonwatmore.com/post/2019/02/07/angular-7-communicating-between-components-with-observable-subject 6/10
2/13/2019 Angular 7 - Communicating Between Components with Observable & Subject | Jason Watmore's Blog

Angular 7 - JWT Authentication Example & Tutorial (/post/2018/11/16/angular-7-jwt-


authentication-example-tutorial)
Angular 7 - Template-Driven Forms Validation Example (/post/2018/11/10/angular-7-
template-driven-forms-validation-example)
Angular 7 - Reactive Forms Validation Example (/post/2018/11/07/angular-7-reactive-
Sponsored by 
forms-validation-example)
Angular 7 - User Registration and Login Example & Tutorial (/post/2018/10/29/angular-
7-user-registration-and-login-example-tutorial)

(//srv.carbonads.n
et/ads/click/x/GT
ND42QMCTYDVK
7MF6A4YKQMCE
AIL53WCYSI6Z3JC
WBDL537CVSIKK
QKC6BIPK3ECKSI
KK3EHJNCLSIZ?
segment=placem
ent:jasonwatmore
;)

The new generation


of project
management tools is
here and it’s visual.
(//srv.carbonads.net/
ads/click/x/GTND42
QMCTYDVK7MF6A4Y
KQMCEAIL53WCYSI6
Z3JCWBDL537CVSIK
KQKC6BIPK3ECKSIK
K3EHJNCLSIZ?
segment=placement:
jasonwatmore;)

ads via Carbon


(http://carbonads.ne
t/?
utm_source=jasonw
atmore&utm_mediu
m=ad_via_link&utm
_campaign=in_unit&
utm_term=carbon)

Supporter devv.jobs skills vs tech-stack matching 🤔anonymous&&free 😲 community contributed 😍


(https://codefund.app/impressions/d1c4bd9f-6f6f-40bd-97fb-a9d12e229b06/click?campaign_id=156) ethical ad by CodeFund
(https://codefund.app/?ref=d1c4bd9f-6f6f-40bd-97fb-a9d12e229b06)

http://jasonwatmore.com/post/2019/02/07/angular-7-communicating-between-components-with-observable-subject 7/10
2/13/2019 Angular 7 - Communicating Between Components with Observable & Subject | Jason Watmore's Blog

What do you think?


1 Response

Upvote Funny Love Surprised Angry Sad

Sponsored by 
0 Comments Jason Watmore's Blog 
1 Login

 Recommend t Tweet f Share Sort by Best

Start the discussion… (//srv.carbonads.n


et/ads/click/x/GT
LOG IN WITH
OR SIGN UP WITH DISQUS ? ND42QMCTYDVK
7MF6A4YKQMCE
Name
AIL53WCYSI6Z3JC
WBDL537CVSIKK
QKC6BIPK3ECKSI
KK3EHJNCLSIZ?
segment=placem
Be the first to comment. ent:jasonwatmore
;)

The new generation


of project
ALSO ON JASON WATMORE'S BLOG management tools is
Vue + Vuex - User Registration and Login Vue.js + VeeValidate - Form here and it’s visual.
Validation Example
(//srv.carbonads.net/
Tutorial & Example | Jason … | Jason Watmore's Blog ads/click/x/GTND42
9 comments • 7 months ago 1 comment • 6 months ago QMCTYDVK7MF6A4Y
DeryckOE — Great Job Jason.Works perfect! I'm san — How can I use input or KQMCEAIL53WCYSI6
onInput instead of
Avatarnow modifying in order to make it work with Z3JCWBDL537CVSIK
Avatarsubmitted for email validation ?" :class="{ 'is-
WordPress as … invalid': submitted && … KQKC6BIPK3ECKSIK
K3EHJNCLSIZ?
NodeJS - Basic Authentication Tutorial with segment=placement:
Angular 6 - Basic HTTP Authentication Tutorial
jasonwatmore;)
Example API | Jason … & Example …
1 comment • 5 months ago ads via Carbon
4 comments • 5 months ago
(http://carbonads.ne
HACKSCOMICON AKA: HAX — the api is not Srini — login page loads for me but when i submit
t/?
Avatardocumented and I have a hard time understanding Avatarthe page i get a 'Username or password incorrect'
utm_source=jasonw
it. … atmore&utm_mediu
m=ad_via_link&utm
✉ Subscribe d Add Disqus to your siteAdd DisqusAdd 🔒 Disqus' Privacy PolicyPrivacy PolicyPrivacy _campaign=in_unit&
utm_term=carbon)

Supporter devv.jobs skills vs tech-stack matching 🤔anonymous&&free 😲 community contributed 😍


(https://codefund.app/impressions/d1c4bd9f-6f6f-40bd-97fb-a9d12e229b06/click?campaign_id=156) ethical ad by CodeFund
(https://codefund.app/?ref=d1c4bd9f-6f6f-40bd-97fb-a9d12e229b06)

http://jasonwatmore.com/post/2019/02/07/angular-7-communicating-between-components-with-observable-subject 8/10
2/13/2019 Angular 7 - Communicating Between Components with Observable & Subject | Jason Watmore's Blog

ABOUT

I'm a web developer in Sydney Australia and the technical lead at Point Blank Development
(https://www.pointblankdevelopment.com.au), I've been building websites and web
Sponsored by 
applications in Sydney since 1998.

Find me on:  (https://twitter.com/jason_watmore)


 (https://github.com/cornflourblue)
(//srv.carbonads.n
 (http://stackoverflow.com/users/2955770/jason)
et/ads/click/x/GT
ND42QMCTYDVK
Support me on Patreon (https://www.patreon.com/jasonwatmore) 7MF6A4YKQMCE
AIL53WCYSI6Z3JC
WBDL537CVSIKK
QKC6BIPK3ECKSI
MONTHS KK3EHJNCLSIZ?
segment=placem
2019 ent:jasonwatmore
;)
February (/posts/2019/02) (3)
January (/posts/2019/01) (1) The new generation
of project
2018
management tools is
2017 here and it’s visual.
2016 (//srv.carbonads.net/
2015 ads/click/x/GTND42
QMCTYDVK7MF6A4Y
2014 KQMCEAIL53WCYSI6
2013 Z3JCWBDL537CVSIK
2012 KQKC6BIPK3ECKSIK
K3EHJNCLSIZ?
2011
segment=placement:
TAGS jasonwatmore;)

ads via Carbon


(http://carbonads.ne
Angular 2, Angular 4, Angular 5, Angular 6, Angular 7, Angular Directive, t/?
Angular UI Router, AngularJS, Animation, ASP.NET, ASP.NET Core, ASP.NET Web API,
utm_source=jasonw
atmore&utm_mediu
Authentication and Authorization, AWS, Basic Authentication, Bootstrap, C#, Chai,
m=ad_via_link&utm
CKEditor, CSS3, DDD, Design Patterns, Dynamic LINQ, ELMAH, ES6, Exchange, _campaign=in_unit&
Facebook, Fluent NHibernate, Google Analytics, Google API, Google Maps API,
utm_term=carbon)
Google Plus, Heroku,
Supporter HTML5,
devv.jobs skills vsHTTP, IIS,matching
tech-stack Insecure Content, Instagram
🤔anonymous&&free API,
😲 community contributed 😍
Ionic Framework, iOS, iPhone, JavaScript, jQuery, JWT, LinkedIn, LINQ, ethical
(https://codefund.app/impressions/d1c4bd9f-6f6f-40bd-97fb-a9d12e229b06/click?campaign_id=156) Login, ad by CodeFund
MEAN Stack, Mocha, Modal, MongoDB, Moq, MVC, MVC5, NGINX, ngMock, NHibernate,
(https://codefund.app/?ref=d1c4bd9f-6f6f-40bd-97fb-a9d12e229b06)

http://jasonwatmore.com/post/2019/02/07/angular-7-communicating-between-components-with-observable-subject 9/10
2/13/2019 Angular 7 - Communicating Between Components with Observable & Subject | Jason Watmore's Blog

Ninject, NodeJS, npm, Pagination, Pinterest, Razor Pages, React, Redmine, Redux,
Registration, Repository, RxJS, Security, Shell Scripting, Sinon, SinonJS, TDD, Terraform,
Twitter, TypeScript, Ubuntu, Umbraco, Unit of Work, Unit Testing, URL Rewrite,
Validation, Vue, Vuex, Windows Server 2008,

Sponsored by 

Powered by MEANie (http://jasonwatmore.com/post/2016/10/29/meanie-mean-stack-blogging-


platform)
© 2019 JasonWatmore.com

(//srv.carbonads.n
et/ads/click/x/GT
ND42QMCTYDVK
7MF6A4YKQMCE
AIL53WCYSI6Z3JC
WBDL537CVSIKK
QKC6BIPK3ECKSI
KK3EHJNCLSIZ?
segment=placem
ent:jasonwatmore
;)

The new generation


of project
management tools is
here and it’s visual.
(//srv.carbonads.net/
ads/click/x/GTND42
QMCTYDVK7MF6A4Y
KQMCEAIL53WCYSI6
Z3JCWBDL537CVSIK
KQKC6BIPK3ECKSIK
K3EHJNCLSIZ?
segment=placement:
jasonwatmore;)

ads via Carbon


(http://carbonads.ne
t/?
utm_source=jasonw
atmore&utm_mediu
m=ad_via_link&utm
_campaign=in_unit&
utm_term=carbon)

Supporter devv.jobs skills vs tech-stack matching 🤔anonymous&&free 😲 community contributed 😍


(https://codefund.app/impressions/d1c4bd9f-6f6f-40bd-97fb-a9d12e229b06/click?campaign_id=156) ethical ad by CodeFund
(https://codefund.app/?ref=d1c4bd9f-6f6f-40bd-97fb-a9d12e229b06)

http://jasonwatmore.com/post/2019/02/07/angular-7-communicating-between-components-with-observable-subject 10/10

Вам также может понравиться