Skip to content

Instantly share code, notes, and snippets.

@joshcaplin
Last active April 22, 2016 02:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshcaplin/2cd1916c5c85def5f4a2e23b92642166 to your computer and use it in GitHub Desktop.
Save joshcaplin/2cd1916c5c85def5f4a2e23b92642166 to your computer and use it in GitHub Desktop.
Angular2, Angular 2, AngularJS2, AngularJS 2, example with HTTP GET, Beta 15, TypeScript

Simple Angular 2 example with service for HTTP call

  • These are the core files I used for my Angular 2 test, it's based on the Beta 15 release, so keep that in mind if you're using a different version.
  • If you're just starting out, be careful with basing your code on outdated information - the syntax has changed a lot through the Alpha and Beta versions.
  • I set up the http GET to call a server side ASP .NET MVC action, which calls the SWAPI (Star Wars API) and returns the data back to the browser. You may need to adjust this part of it, if you want to handle the call differently, get the data back in a different format, etc.
  • This is setup to use the transpiled Javascript code (see index.html where it specifies default extension of 'js'. As a shortcut you can use your raw TypeScript code, but this will significantly slow down your page because you need to load the huge typescript.js library and it needs to transpile the code on-the-fly.
  • I added this into an existing Angular 1.x app, so I made some minor adjustments from the official guide. Notice the templateUrl specifies 'app2/starWarsSearch.component.html' in starWarsSearch.component.ts - 'app2' was the folder I put all the TypeScript files in, so adjust that path if you have your files in a different location.
  • This was my very first attempt at Angular 2, so I'm sure there are improvements that can be made. I'll try to update this as I find them.
import {Injectable} from 'angular2/core';
@Injectable()
export class Character {
id: number;
name: string;
BirthYear: string;
Height: string;
EyeColor: string;
Gender: string;
SpeciesName: string;
SpeciesLanguage: string;
SpeciesLifespan: string;
PlanetName: string;
PlanetPopulation: string;
}
*** Add this code where you want to initialize the Angular2 app.
*** This loads key libraries, then configures & bootstraps your Angular2 app
*** DO NOT load the typescript.js script unless you're using TypeScript files instead of JS files - it is significantly slower to use TS files
************************************************************************
<script src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.35.0/es6-shim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.26/system-polyfills.js"></script>
<script src="https://npmcdn.com/angular2@2.0.0-beta.15/es6/dev/src/testing/shims_for_IE.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.15/angular2-polyfills.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.26/system.js"></script>
<script src="https://npmcdn.com/typescript@1.8.10/lib/typescript.js"></script> <<<<<---------------- PROBABLY NOT NEEDED
<script src="https://code.angularjs.org/2.0.0-beta.15/Rx.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.15/angular2.dev.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.15/http.dev.js"></script>
<script src="https://npmcdn.com/a2-in-memory-web-api/web-api.js"></script>
<script>
System.config({
transpiler: 'typescript',
typescriptOptions: { emitDecoratorMetadata: true },
packages: { 'app2': { defaultExtension: 'js' } },
map: {'app2': './app2'}
});
System.import('app2/main')
.then(null, console.error.bind(console));
</script>
import {bootstrap} from 'angular2/platform/browser';
import {HTTP_PROVIDERS} from 'angular2/http';
// Add all operators to Observable
import 'rxjs/Rx';
import { StarWarsSearchComponent } from './starWarsSearch.component';
bootstrap(StarWarsSearchComponent, [HTTP_PROVIDERS]);
<h4>Star Wars Character Lookup</h4>
<p class="smallBottomMargin">Enter a numeric value to lookup a Star Wars character (i.e. Luke Skywalker = 1). <span class="text-info"><i>(Future improvement: search by name.)</i></span></p>
<div class="input-group">
<input type="text" class="form-control cancel-card-flip" placeholder="1" [(ngModel)]="searchId">
<span class="input-group-btn">
<button class="btn btn-primary" type="button" (click)="search();">Search!</button>
</span>
</div>
<div *ngIf="isSearching" class="text-center">
<br/>
<br/>
<span class="h3 text-primary">Getting data...</span>
</div>
<div *ngIf="character && !isSearching">
<ul>
<li>Character: {{ character[0].Name }}</li>
<li>Language: {{ character[0].SpeciesLanguage }}</li>
<li>Height: {{ character[0].Height }}</li>
<li>Species: {{ character[0].SpeciesName }}</li>
<li>Species Avg Lifespan: {{ character[0].SpeciesLifespan }}</li>
<li>Home Planet: {{ character[0].PlanetName }}</li>
<li>Planet Population: {{ character[0].PlanetPopulation }}</li>
</ul>
</div>
<ul>
<li *ngFor="#item of items | async">{{item}}</li>
</ul>
import {Component, OnInit} from 'angular2/core';
import {JSONP_PROVIDERS} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
import {Character} from './character';
import {StarWarsSearchService} from './starWarsSearch.service';
@Component({
selector: 'star-wars-lookup',
templateUrl: 'app2/starWarsSearch.component.html',
providers: [JSONP_PROVIDERS, StarWarsSearchService]
})
export class StarWarsSearchComponent implements OnInit{
constructor(private _starWarsSearchService: StarWarsSearchService) { }
errorMessage: string;
character: Character[];
searchId: string = "";
isSearching: boolean = false;
search(term: string) {
this.isSearching = true;
this._starWarsSearchService.search(this.searchId).subscribe(
data => this.character = data,
err => console.error(err),
() => this.isSearching = false);
}
}
import {Injectable} from 'angular2/core';
import {Http, Response} from 'angular2/http';
import {Jsonp, URLSearchParams} from 'angular2/http';
import {Character} from './character';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class StarWarsSearchService {
constructor(private jsonp: Jsonp, private _http: Http) { }
search(term: string) : Observable<Character[]>{
let dataUrl = '/Demos/LookupStarWarsCharacter';
return this._http.get(dataUrl + "/" + term)
.map((res: Response) => res.json())
.catch(this.handleError);
}
handleError(error: any) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment