RxJS in Angular page
Learn how to read and write observables in Angular.
Video
Who has time to read? This video covers the content on this page. Watch fullscreen.
The problem
In this section, we will:
- Create a CodePen setup with Angular and the HTML of our form.
- Write values to a Subject and write out the value of the subject in the template.
Observables and the $ suffix
At Bitovi, we follow the ts.dev Style Guide and prefer to suffix Observables with $
.
Although not enforced, it is useful to visually differentiate between observable and non-observable values.
How to solve this problem
- Create a
userCardNumber$
BehaviorSubject
. - Write the value of the
cardNumber
input to theuserCardNumber$
BehaviorSubject
on theinput
event. - Write the value of
cardNumber
out in the template under the</form>
element like:
What you need to know
Click "Run in your browser" at the bottom of the following example to launch a CodePen with Angular and the HTML of the credit card form. You will edit this CodePen for the remainder of this tutorial.
Initialize a BehaviorSubject instance on a class
like the following:
A BehaviorSubject
is just like a Subject
except that it
remembers its last value. Any new subscribers will immediately
be sent the last value.
Emit a value on a Subject by calling subject.next()
:
You can call subject.next()
in the DOM as follows:
Use | async
to write out an observable’s value in a template as follows:
Read more about this technique here.