Using RxJS subject to broadcast an HTTP response.
- [Instructor] Instead of allowing components to access our messages array directly, which might not be safe, we can use an observable, specifically a subject. A subject allows observers to subscribe to it, and in this case we can send our messages array through it, whenever an update through an HTTP request occurs. Let's begin by importing subject from the RxJS library into our web service.
As you can see in line four, I've imported that from rxjs slash rx, and now let's create a messageSubject field. Next, inside our getMessages response handler, let's call messageSubject dot next and pass in our message store. This will let any observer, such as our message components, which will subscribe to our message subject, know that there is probably an update, and we will pass along the message array to provide the observer with the messages.
Since we will be passing our messages through the subject, our messages array no longer needs to be public, so let's make that private. Next, we need to subscribe to our message subject. So let's go inside our messages component to do that. Inside the ngOnInit, let's access the subject through the web service. Now let's create a local message list in the class so that we can set it to whatever we get back from the subject. And on our message subject, we'll call dot subscribe, and we'll be getting back our messages.
And we'll set that to this dot messages equal messages. Next let's go back to our template in our message components, and update the for loops so we are no longer directly accessing the messages from the web service. And since we have a local copy of the messages, let's loop through that. Let's give this a try. And it seems to still be working. But now, the message array is no longer publicly exposed in our web service, and so we have a bit more of added security, but there is a problem.
Since we are exposing the subject, we can call next on it from outside of the service. This could be bad because we could accidentally pass in some data from another component. Let's put in some safety by exposing an observable instead of the subject. Let's take a look at that next.
- Setting up the infrastructure
- Displaying data in Angular 2
- Refining your layout with Angular Material
- Getting your data from Node.js
- Saving data to a list
- Creating the component
- Getting your input data
- Creating reactive forms in Angular
- Creating a security middleware
Skill Level Intermediate
Q: This course was updated on 10/17/2017. What changed?
A: We updated five videos to reflect changes to the setup and data retrieval and display processes in Angular 2. For example, instead of using a Git Angular template, the updated course uses the Angular CLI to generate a starting template, for a smooth runtime experience.