1. Describe publish/subscribe model and how it relates to Observables
1. Demonstrate when a normal promise is not optimal
1. Switch from a Promise to an Observable
1. Make typing into an input field an observable
## Describe publish/subscribe model and how it relates to Observables
@ -47,3 +48,71 @@ Since we aren't using `toPromise` anymore, we can eliminate this line of code in
```javascript
import 'rxjs/add/operator/toPromise';
```
## Make typing into an input field an observable
`this.http.get()` returns an observable, but how can we make our own? Let's make typing into the input field an observable action. To do this, we'll need to import the `Subject` module from `rxjs` in `src/app/search/search.component.ts`:
```javascript
import { Subject } from 'rxjs/Subject'
```
A Subject, is just like an Observable, but it allows us to tell it when to publish events. Let's create a property on `SearchComponent` that is a `Subject` that we'll tell to publish events when the user types.
```javascript
export class SearchComponent implements OnInit {
results;
searchSubject = new Subject(); //add this property
Now we want to tell the `SearchComponent` to subscribe to those events that we publish with `this.searchSubject.next(name);`. In `ngOnInit`, add this:
```javascript
ngOnInit() {
this.searchSubject.subscribe(name => {
console.log(name);
})
}
```
When `SearchComponent` is initialized, it sets up a subscription to the `searchSubject` observable. When `searchSubject` publishes an event, the code above logs the name that was written.
Instead of logging the name, though, we want to make an AJAX call. Move the `this.http.get()` code into the `subscribe` callback: