From 1dedf84586e5cc23338e90ba9741d70a61c75c5d Mon Sep 17 00:00:00 2001 From: Matt Huntington Date: Mon, 26 Jun 2017 21:50:23 -0400 Subject: [PATCH] Switch from a Promise to an Observable --- day3/README.md | 18 ++++++++++++++++++ .../src/app/search/search.component.ts | 4 +--- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/day3/README.md b/day3/README.md index c80a8e0..17e1ae1 100644 --- a/day3/README.md +++ b/day3/README.md @@ -4,6 +4,7 @@ 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 ## Describe publish/subscribe model and how it relates to Observables @@ -27,3 +28,20 @@ Firstly, we want it to search as the user types into the input (like how google ``` Test it out. In the network tab of your Chrome Developer Tools, see how a request goes out for every letter? And they don't always come back in order, either. With Observables, we can fix this. + +## Switch from a Promise to an Observable + +In `src/app/search/search.component.ts` edit the `findCharacter` method of `SearchComponent`. + +```javascript +findCharacter(name){ + this.http.get('http://swapi.co/api/people/?search=' + name) + .subscribe(response => this.results = response.json().results); +} +``` + +Since we aren't using `toPromise` anymore, we can eliminate this line of code in `src/app/search/search.component.ts` + +```javascript +import 'rxjs/add/operator/toPromise'; +``` diff --git a/day3/starwars/src/app/search/search.component.ts b/day3/starwars/src/app/search/search.component.ts index a02bf38..b045136 100644 --- a/day3/starwars/src/app/search/search.component.ts +++ b/day3/starwars/src/app/search/search.component.ts @@ -1,6 +1,5 @@ import { Component, OnInit } from '@angular/core'; import { Http } from '@angular/http'; -import 'rxjs/add/operator/toPromise'; @Component({ selector: 'app-search', @@ -17,8 +16,7 @@ export class SearchComponent implements OnInit { findCharacter(name){ this.http.get('http://swapi.co/api/people/?search=' + name) - .toPromise() - .then(response => this.results = response.json().results); + .subscribe(response => this.results = response.json().results); } ngOnInit() {