From 07a1f2fb027b0a12d55654b8f9982752ce4450a7 Mon Sep 17 00:00:00 2001 From: Matt Huntington Date: Tue, 20 Jun 2017 17:39:09 -0400 Subject: [PATCH] Add the ability to make AJAX requests --- starwars/src/app/app.module.ts | 2 ++ starwars/src/app/search/search.component.ts | 6 +++- use_an_api.md | 38 +++++++++++++++++++++ 3 files changed, 45 insertions(+), 1 deletion(-) diff --git a/starwars/src/app/app.module.ts b/starwars/src/app/app.module.ts index 2898cc4..c57e8df 100644 --- a/starwars/src/app/app.module.ts +++ b/starwars/src/app/app.module.ts @@ -5,6 +5,7 @@ import { AppComponent } from './app.component'; import { SearchComponent } from './search/search.component'; import { FormsModule } from '@angular/forms'; +import { HttpModule } from '@angular/http'; @NgModule({ declarations: [ @@ -13,6 +14,7 @@ import { FormsModule } from '@angular/forms'; ], imports: [ BrowserModule, + HttpModule, FormsModule ], providers: [], diff --git a/starwars/src/app/search/search.component.ts b/starwars/src/app/search/search.component.ts index e3a5693..cbedad5 100644 --- a/starwars/src/app/search/search.component.ts +++ b/starwars/src/app/search/search.component.ts @@ -1,4 +1,6 @@ import { Component, OnInit } from '@angular/core'; +import { Http } from '@angular/http'; +import 'rxjs/add/operator/toPromise'; @Component({ selector: 'app-search', @@ -7,7 +9,9 @@ import { Component, OnInit } from '@angular/core'; }) export class SearchComponent implements OnInit { - constructor() { } + constructor( + private http: Http + ) { } findCharacter(name){ console.log('finding ' + name); diff --git a/use_an_api.md b/use_an_api.md index 87a9c1b..749ab79 100644 --- a/use_an_api.md +++ b/use_an_api.md @@ -10,6 +10,7 @@ 1. Import Form functionality into the app 1. Set a component property to the value of an input 1. Invoke a function when the user clicks a button +1. Add the ability to make AJAX requests ## Create a new app @@ -118,3 +119,40 @@ Call it in `src/app/search/search.component.html` (also remove the `Search Strin ``` Test this by looking in the console + +## Add the ability to make AJAX requests + +Add `HttpModule` to `src/app/app.module.ts`: + +```javascript +import { HttpModule } from '@angular/http'; //import module + +@NgModule({ + declarations: [ + AppComponent, + SearchComponent + ], + imports: [ + BrowserModule, + HttpModule, //add HttpModule here + FormsModule + ], + providers: [], + bootstrap: [AppComponent] +}) +``` + +Now edit `src/app/search/search.component.ts` to import appropriate modules: + +```javascript +import { Http } from '@angular/http'; +import 'rxjs/add/operator/toPromise'; +``` + +And tell the constructor of the `SearchComponent` class to add an `http` property: + +```javascript +constructor( + private http: Http +) { } +```