Angular 4 allows sending async/sync request with one more concept called Observable apart from Promises. This is leveraged via RxJS library. Observables are based on Observer design pattern. Let’s take a quick detour prior to delving into Observables what the Observer design pattern is all about.
Think about it this way. Let’s say you are subscribing to any TV channel of interest. In this case you are Observer (among a list of subscribers) and the channel is a point of interest (technically called as Subject or Observable). The Subject maintains logic to register an Observer. The Subject notifies the observers through a call to their internal logic. This creates a separation of concerns. Regardless, I digress. This is a story (read blog post) for another time.
Moving on to Observable in Angular. Let’s suppose the backend is sending across Movie details. This will be a REST call in the form of sending back a JSON.
In our service class we will hit the Spring backend and ask for a response for a list of those movies persisted on the server. The http.get constructs an Observables that the MovieList Component can subscribe to. Following is the relevant piece of code:
Now in our component, we call the above method in the service. This being an observable we subscribe to it. We use something along the lines of:Think about it this way. Let’s say you are subscribing to any TV channel of interest. In this case you are Observer (among a list of subscribers) and the channel is a point of interest (technically called as Subject or Observable). The Subject maintains logic to register an Observer. The Subject notifies the observers through a call to their internal logic. This creates a separation of concerns. Regardless, I digress. This is a story (read blog post) for another time.
Moving on to Observable in Angular. Let’s suppose the backend is sending across Movie details. This will be a REST call in the form of sending back a JSON.
In our service class we will hit the Spring backend and ask for a response for a list of those movies persisted on the server. The http.get constructs an Observables that the MovieList Component can subscribe to. Following is the relevant piece of code:
getMovies (): Observable<Movie> { return this.http.get<Movie>(this.movieUrl); }
getMovies(): void { this.movieService.getMovies() .subscribe(movies => this.movies = movies, error => console.log("Error :: " + error)) }
The above console statement was just for the sake of it as this is a contrived example.
And this can be in turn iterated over in our template by means of ngFor. This I believe has just scratched the surface. Later on I will cover the different operators on the Observables.
No comments:
Post a Comment