Use 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 on line four, I've imported that from rxjs/rx. And now, let's create a message subject field. Next inside our get messages response handler, let's call message subject dot next and pass in our message store. This will let any observer, such as our message components, which was subscribed 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 subjects 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.messages = messages. Next let's go back to our template in our message components and update the for loop 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 observerable instead of the subject. Let's take a look at that next.
- Setting up the app infrastructure
- Creating and configuring the Angular 2 project
- Displaying data in Angular
- Refining the layout
- Creating the ASP.NET Core project
- Creating a controller with ASP.NET Core
- Creating a nav bar
- Registering users
- Authorizing resources
Skill Level Intermediate
Q: This course was updated on 10/18/2017. What changed?
A: The following topics were updated: setting up the app infrastructure, displaying data in Angular 2, getting data from ASP.NET Core, creating a controller with ASP.NET Core, and authorizing resources.