feat(aio): copy example code from angular.io
This commit is contained in:

committed by
Igor Minar

parent
3e34ba01bd
commit
1f3198cb50
10
aio/content/examples/server-communication/ts/plnkr.json
Normal file
10
aio/content/examples/server-communication/ts/plnkr.json
Normal file
@ -0,0 +1,10 @@
|
||||
{
|
||||
"description": "Http",
|
||||
"basePath": "src/",
|
||||
"files":[
|
||||
"!**/*.d.ts",
|
||||
"!**/*.js",
|
||||
"!**/*.[1].*"
|
||||
],
|
||||
"tags": ["http", "jsonp"]
|
||||
}
|
610
aio/content/examples/server-communication/ts/plnkr.no-link.html
Normal file
610
aio/content/examples/server-communication/ts/plnkr.no-link.html
Normal file
@ -0,0 +1,610 @@
|
||||
<html lang="en"><head></head><body><form id="mainForm" method="post" action="http://plnkr.co/edit/?p=preview" target="_self"><input type="hidden" name="files[app/app.component.ts]" value="import { Component } from '@angular/core';
|
||||
|
||||
@Component({
|
||||
selector: 'my-app',
|
||||
template: `
|
||||
<hero-list></hero-list>
|
||||
<hero-list-promise></hero-list-promise>
|
||||
<my-wiki></my-wiki>
|
||||
<my-wiki-smart></my-wiki-smart>
|
||||
`
|
||||
})
|
||||
export class AppComponent { }
|
||||
|
||||
|
||||
/*
|
||||
Copyright 2016 Google Inc. All Rights Reserved.
|
||||
Use of this source code is governed by an MIT-style license that
|
||||
can be found in the LICENSE file at http://angular.io/license
|
||||
*/"><input type="hidden" name="files[app/app.module.ts]" value="import { NgModule } from '@angular/core';
|
||||
import { BrowserModule } from '@angular/platform-browser';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { HttpModule, JsonpModule } from '@angular/http';
|
||||
|
||||
|
||||
import { InMemoryWebApiModule } from 'angular-in-memory-web-api';
|
||||
import { HeroData } from './hero-data';
|
||||
import { requestOptionsProvider } from './default-request-options.service';
|
||||
|
||||
import { AppComponent } from './app.component';
|
||||
|
||||
import { HeroListComponent } from './toh/hero-list.component';
|
||||
import { HeroListPromiseComponent } from './toh/hero-list.component.promise';
|
||||
|
||||
import { WikiComponent } from './wiki/wiki.component';
|
||||
import { WikiSmartComponent } from './wiki/wiki-smart.component';
|
||||
|
||||
@NgModule({
|
||||
imports: [
|
||||
BrowserModule,
|
||||
FormsModule,
|
||||
HttpModule,
|
||||
JsonpModule,
|
||||
InMemoryWebApiModule.forRoot(HeroData)
|
||||
],
|
||||
declarations: [
|
||||
AppComponent,
|
||||
HeroListComponent,
|
||||
HeroListPromiseComponent,
|
||||
WikiComponent,
|
||||
WikiSmartComponent
|
||||
],
|
||||
providers: [ requestOptionsProvider ],
|
||||
bootstrap: [ AppComponent ]
|
||||
})
|
||||
export class AppModule {}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/*
|
||||
Copyright 2016 Google Inc. All Rights Reserved.
|
||||
Use of this source code is governed by an MIT-style license that
|
||||
can be found in the LICENSE file at http://angular.io/license
|
||||
*/"><input type="hidden" name="files[app/default-request-options.service.ts]" value="import { Injectable } from '@angular/core';
|
||||
import { BaseRequestOptions, RequestOptions } from '@angular/http';
|
||||
|
||||
@Injectable()
|
||||
export class DefaultRequestOptions extends BaseRequestOptions {
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
// Set the default 'Content-Type' header
|
||||
this.headers.set('Content-Type', 'application/json');
|
||||
}
|
||||
}
|
||||
|
||||
export const requestOptionsProvider = { provide: RequestOptions, useClass: DefaultRequestOptions };
|
||||
|
||||
|
||||
/*
|
||||
Copyright 2016 Google Inc. All Rights Reserved.
|
||||
Use of this source code is governed by an MIT-style license that
|
||||
can be found in the LICENSE file at http://angular.io/license
|
||||
*/"><input type="hidden" name="files[app/hero-data.ts]" value="import { InMemoryDbService } from 'angular-in-memory-web-api';
|
||||
export class HeroData implements InMemoryDbService {
|
||||
createDb() {
|
||||
let heroes = [
|
||||
{ id: 1, name: 'Windstorm' },
|
||||
{ id: 2, name: 'Bombasto' },
|
||||
{ id: 3, name: 'Magneta' },
|
||||
{ id: 4, name: 'Tornado' }
|
||||
];
|
||||
return {heroes};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
Copyright 2016 Google Inc. All Rights Reserved.
|
||||
Use of this source code is governed by an MIT-style license that
|
||||
can be found in the LICENSE file at http://angular.io/license
|
||||
*/"><input type="hidden" name="files[app/toh/hero-list.component.promise.ts]" value="// Promise Version
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
import { Hero } from './hero';
|
||||
import { HeroService } from './hero.service.promise';
|
||||
|
||||
@Component({
|
||||
selector: 'hero-list-promise',
|
||||
moduleId: module.id,
|
||||
templateUrl: './hero-list.component.html',
|
||||
providers: [ HeroService ],
|
||||
styles: ['.error {color:red;}']
|
||||
})
|
||||
export class HeroListPromiseComponent implements OnInit {
|
||||
errorMessage: string;
|
||||
heroes: Hero[];
|
||||
mode = 'Promise';
|
||||
|
||||
constructor (private heroService: HeroService) {}
|
||||
|
||||
ngOnInit() { this.getHeroes(); }
|
||||
|
||||
getHeroes() {
|
||||
this.heroService.getHeroes()
|
||||
.then(
|
||||
heroes => this.heroes = heroes,
|
||||
error => this.errorMessage = <any>error);
|
||||
}
|
||||
|
||||
addHero (name: string) {
|
||||
if (!name) { return; }
|
||||
this.heroService.addHero(name)
|
||||
.then(
|
||||
hero => this.heroes.push(hero),
|
||||
error => this.errorMessage = <any>error);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
Copyright 2016 Google Inc. All Rights Reserved.
|
||||
Use of this source code is governed by an MIT-style license that
|
||||
can be found in the LICENSE file at http://angular.io/license
|
||||
*/"><input type="hidden" name="files[app/toh/hero-list.component.ts]" value="// Observable Version
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
import { Hero } from './hero';
|
||||
import { HeroService } from './hero.service';
|
||||
|
||||
@Component({
|
||||
moduleId: module.id,
|
||||
selector: 'hero-list',
|
||||
templateUrl: './hero-list.component.html',
|
||||
providers: [ HeroService ],
|
||||
styles: ['.error {color:red;}']
|
||||
})
|
||||
export class HeroListComponent implements OnInit {
|
||||
errorMessage: string;
|
||||
heroes: Hero[];
|
||||
mode = 'Observable';
|
||||
|
||||
constructor (private heroService: HeroService) {}
|
||||
|
||||
ngOnInit() { this.getHeroes(); }
|
||||
|
||||
getHeroes() {
|
||||
this.heroService.getHeroes()
|
||||
.subscribe(
|
||||
heroes => this.heroes = heroes,
|
||||
error => this.errorMessage = <any>error);
|
||||
}
|
||||
|
||||
addHero (name: string) {
|
||||
if (!name) { return; }
|
||||
this.heroService.addHero(name)
|
||||
.subscribe(
|
||||
hero => this.heroes.push(hero),
|
||||
error => this.errorMessage = <any>error);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
Copyright 2016 Google Inc. All Rights Reserved.
|
||||
Use of this source code is governed by an MIT-style license that
|
||||
can be found in the LICENSE file at http://angular.io/license
|
||||
*/"><input type="hidden" name="files[app/toh/hero.service.promise.ts]" value="// Promise Version
|
||||
import { Injectable } from '@angular/core';
|
||||
import { Http, Response } from '@angular/http';
|
||||
import { Headers, RequestOptions } from '@angular/http';
|
||||
|
||||
import 'rxjs/add/operator/toPromise';
|
||||
|
||||
import { Hero } from './hero';
|
||||
|
||||
@Injectable()
|
||||
export class HeroService {
|
||||
// URL to web api
|
||||
private heroesUrl = 'app/heroes';
|
||||
|
||||
constructor (private http: Http) {}
|
||||
|
||||
getHeroes (): Promise<Hero[]> {
|
||||
return this.http.get(this.heroesUrl)
|
||||
.toPromise()
|
||||
.then(this.extractData)
|
||||
.catch(this.handleError);
|
||||
}
|
||||
|
||||
addHero (name: string): Promise<Hero> {
|
||||
let headers = new Headers({ 'Content-Type': 'application/json' });
|
||||
let options = new RequestOptions({ headers: headers });
|
||||
|
||||
return this.http.post(this.heroesUrl, { name }, options)
|
||||
.toPromise()
|
||||
.then(this.extractData)
|
||||
.catch(this.handleError);
|
||||
}
|
||||
|
||||
private extractData(res: Response) {
|
||||
let body = res.json();
|
||||
return body.data || { };
|
||||
}
|
||||
|
||||
private handleError (error: Response | any) {
|
||||
// In a real world app, we might use a remote logging infrastructure
|
||||
let errMsg: string;
|
||||
if (error instanceof Response) {
|
||||
const body = error.json() || '';
|
||||
const err = body.error || JSON.stringify(body);
|
||||
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
|
||||
} else {
|
||||
errMsg = error.message ? error.message : error.toString();
|
||||
}
|
||||
console.error(errMsg);
|
||||
return Promise.reject(errMsg);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
Copyright 2016 Google Inc. All Rights Reserved.
|
||||
Use of this source code is governed by an MIT-style license that
|
||||
can be found in the LICENSE file at http://angular.io/license
|
||||
*/"><input type="hidden" name="files[app/toh/hero.service.ts]" value="// Observable Version
|
||||
import { Injectable } from '@angular/core';
|
||||
import { Http, Response } from '@angular/http';
|
||||
import { Headers, RequestOptions } from '@angular/http';
|
||||
|
||||
import { Observable } from 'rxjs/Observable';
|
||||
import 'rxjs/add/operator/catch';
|
||||
import 'rxjs/add/operator/map';
|
||||
|
||||
import { Hero } from './hero';
|
||||
|
||||
@Injectable()
|
||||
export class HeroService {
|
||||
private heroesUrl = 'app/heroes'; // URL to web API
|
||||
|
||||
constructor (private http: Http) {}
|
||||
|
||||
getHeroes (): Observable<Hero[]> {
|
||||
return this.http.get(this.heroesUrl)
|
||||
.map(this.extractData)
|
||||
.catch(this.handleError);
|
||||
}
|
||||
|
||||
addHero (name: string): Observable<Hero> {
|
||||
let headers = new Headers({ 'Content-Type': 'application/json' });
|
||||
let options = new RequestOptions({ headers: headers });
|
||||
|
||||
return this.http.post(this.heroesUrl, { name }, options)
|
||||
.map(this.extractData)
|
||||
.catch(this.handleError);
|
||||
}
|
||||
|
||||
private extractData(res: Response) {
|
||||
let body = res.json();
|
||||
return body.data || { };
|
||||
}
|
||||
|
||||
private handleError (error: Response | any) {
|
||||
// In a real world app, we might use a remote logging infrastructure
|
||||
let errMsg: string;
|
||||
if (error instanceof Response) {
|
||||
const body = error.json() || '';
|
||||
const err = body.error || JSON.stringify(body);
|
||||
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
|
||||
} else {
|
||||
errMsg = error.message ? error.message : error.toString();
|
||||
}
|
||||
console.error(errMsg);
|
||||
return Observable.throw(errMsg);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
private heroesUrl = 'app/heroes.json'; // URL to JSON file
|
||||
*/
|
||||
|
||||
|
||||
/*
|
||||
Copyright 2016 Google Inc. All Rights Reserved.
|
||||
Use of this source code is governed by an MIT-style license that
|
||||
can be found in the LICENSE file at http://angular.io/license
|
||||
*/"><input type="hidden" name="files[app/toh/hero.ts]" value="export class Hero {
|
||||
constructor(
|
||||
public id: number,
|
||||
public name: string) { }
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
Copyright 2016 Google Inc. All Rights Reserved.
|
||||
Use of this source code is governed by an MIT-style license that
|
||||
can be found in the LICENSE file at http://angular.io/license
|
||||
*/"><input type="hidden" name="files[app/wiki/wiki-smart.component.ts]" value="/* tslint:disable: member-ordering forin */
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
|
||||
import { Observable } from 'rxjs/Observable';
|
||||
import 'rxjs/add/operator/debounceTime';
|
||||
import 'rxjs/add/operator/distinctUntilChanged';
|
||||
import 'rxjs/add/operator/switchMap';
|
||||
|
||||
import { Subject } from 'rxjs/Subject';
|
||||
|
||||
import { WikipediaService } from './wikipedia.service';
|
||||
|
||||
@Component({
|
||||
moduleId: module.id,
|
||||
selector: 'my-wiki-smart',
|
||||
template: `
|
||||
<h1>Smarter Wikipedia Demo</h1>
|
||||
<p>Search when typing stops</p>
|
||||
<input #term (keyup)="search(term.value)"/>
|
||||
<ul>
|
||||
<li *ngFor="let item of items | async">{{item}}</li>
|
||||
</ul>`,
|
||||
providers: [ WikipediaService ]
|
||||
})
|
||||
export class WikiSmartComponent implements OnInit {
|
||||
items: Observable<string[]>;
|
||||
|
||||
constructor (private wikipediaService: WikipediaService) {}
|
||||
|
||||
private searchTermStream = new Subject<string>();
|
||||
search(term: string) { this.searchTermStream.next(term); }
|
||||
|
||||
ngOnInit() {
|
||||
this.items = this.searchTermStream
|
||||
.debounceTime(300)
|
||||
.distinctUntilChanged()
|
||||
.switchMap((term: string) => this.wikipediaService.search(term));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
Copyright 2016 Google Inc. All Rights Reserved.
|
||||
Use of this source code is governed by an MIT-style license that
|
||||
can be found in the LICENSE file at http://angular.io/license
|
||||
*/"><input type="hidden" name="files[app/wiki/wiki.component.ts]" value="import { Component } from '@angular/core';
|
||||
import { Observable } from 'rxjs/Observable';
|
||||
|
||||
import { WikipediaService } from './wikipedia.service';
|
||||
|
||||
@Component({
|
||||
selector: 'my-wiki',
|
||||
template: `
|
||||
<h1>Wikipedia Demo</h1>
|
||||
<p>Search after each keystroke</p>
|
||||
<input #term (keyup)="search(term.value)"/>
|
||||
<ul>
|
||||
<li *ngFor="let item of items | async">{{item}}</li>
|
||||
</ul>`,
|
||||
providers: [ WikipediaService ]
|
||||
})
|
||||
export class WikiComponent {
|
||||
items: Observable<string[]>;
|
||||
|
||||
constructor (private wikipediaService: WikipediaService) { }
|
||||
|
||||
search (term: string) {
|
||||
this.items = this.wikipediaService.search(term);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
Copyright 2016 Google Inc. All Rights Reserved.
|
||||
Use of this source code is governed by an MIT-style license that
|
||||
can be found in the LICENSE file at http://angular.io/license
|
||||
*/"><input type="hidden" name="files[app/wiki/wikipedia.service.ts]" value="import { Injectable } from '@angular/core';
|
||||
import { Jsonp, URLSearchParams } from '@angular/http';
|
||||
|
||||
import 'rxjs/add/operator/map';
|
||||
|
||||
@Injectable()
|
||||
export class WikipediaService {
|
||||
constructor(private jsonp: Jsonp) {}
|
||||
|
||||
search (term: string) {
|
||||
|
||||
let wikiUrl = 'http://en.wikipedia.org/w/api.php';
|
||||
|
||||
let params = new URLSearchParams();
|
||||
params.set('search', term); // the user's search value
|
||||
params.set('action', 'opensearch');
|
||||
params.set('format', 'json');
|
||||
params.set('callback', 'JSONP_CALLBACK');
|
||||
|
||||
// TODO: Add error handling
|
||||
return this.jsonp
|
||||
.get(wikiUrl, { search: params })
|
||||
.map(response => <string[]> response.json()[1]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
Copyright 2016 Google Inc. All Rights Reserved.
|
||||
Use of this source code is governed by an MIT-style license that
|
||||
can be found in the LICENSE file at http://angular.io/license
|
||||
*/"><input type="hidden" name="files[main.ts]" value="import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
|
||||
import { AppModule } from './app/app.module';
|
||||
|
||||
platformBrowserDynamic().bootstrapModule(AppModule);
|
||||
|
||||
|
||||
/*
|
||||
Copyright 2016 Google Inc. All Rights Reserved.
|
||||
Use of this source code is governed by an MIT-style license that
|
||||
can be found in the LICENSE file at http://angular.io/license
|
||||
*/"><input type="hidden" name="files[styles.css]" value="/* Master Styles */
|
||||
h1 {
|
||||
color: #369;
|
||||
font-family: Arial, Helvetica, sans-serif;
|
||||
font-size: 250%;
|
||||
}
|
||||
h2, h3 {
|
||||
color: #444;
|
||||
font-family: Arial, Helvetica, sans-serif;
|
||||
font-weight: lighter;
|
||||
}
|
||||
body {
|
||||
margin: 2em;
|
||||
}
|
||||
body, input[text], button {
|
||||
color: #888;
|
||||
font-family: Cambria, Georgia;
|
||||
}
|
||||
a {
|
||||
cursor: pointer;
|
||||
cursor: hand;
|
||||
}
|
||||
button {
|
||||
font-family: Arial;
|
||||
background-color: #eee;
|
||||
border: none;
|
||||
padding: 5px 10px;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
cursor: hand;
|
||||
}
|
||||
button:hover {
|
||||
background-color: #cfd8dc;
|
||||
}
|
||||
button:disabled {
|
||||
background-color: #eee;
|
||||
color: #aaa;
|
||||
cursor: auto;
|
||||
}
|
||||
|
||||
/* Navigation link styles */
|
||||
nav a {
|
||||
padding: 5px 10px;
|
||||
text-decoration: none;
|
||||
margin-right: 10px;
|
||||
margin-top: 10px;
|
||||
display: inline-block;
|
||||
background-color: #eee;
|
||||
border-radius: 4px;
|
||||
}
|
||||
nav a:visited, a:link {
|
||||
color: #607D8B;
|
||||
}
|
||||
nav a:hover {
|
||||
color: #039be5;
|
||||
background-color: #CFD8DC;
|
||||
}
|
||||
nav a.active {
|
||||
color: #039be5;
|
||||
}
|
||||
|
||||
/* items class */
|
||||
.items {
|
||||
margin: 0 0 2em 0;
|
||||
list-style-type: none;
|
||||
padding: 0;
|
||||
width: 24em;
|
||||
}
|
||||
.items li {
|
||||
cursor: pointer;
|
||||
position: relative;
|
||||
left: 0;
|
||||
background-color: #EEE;
|
||||
margin: .5em;
|
||||
padding: .3em 0;
|
||||
height: 1.6em;
|
||||
border-radius: 4px;
|
||||
}
|
||||
.items li:hover {
|
||||
color: #607D8B;
|
||||
background-color: #DDD;
|
||||
left: .1em;
|
||||
}
|
||||
.items li.selected {
|
||||
background-color: #CFD8DC;
|
||||
color: white;
|
||||
}
|
||||
.items li.selected:hover {
|
||||
background-color: #BBD8DC;
|
||||
}
|
||||
.items .text {
|
||||
position: relative;
|
||||
top: -3px;
|
||||
}
|
||||
.items .badge {
|
||||
display: inline-block;
|
||||
font-size: small;
|
||||
color: white;
|
||||
padding: 0.8em 0.7em 0 0.7em;
|
||||
background-color: #607D8B;
|
||||
line-height: 1em;
|
||||
position: relative;
|
||||
left: -1px;
|
||||
top: -4px;
|
||||
height: 1.8em;
|
||||
margin-right: .8em;
|
||||
border-radius: 4px 0 0 4px;
|
||||
}
|
||||
/* everywhere else */
|
||||
* {
|
||||
font-family: Arial, Helvetica, sans-serif;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
Copyright 2016 Google Inc. All Rights Reserved.
|
||||
Use of this source code is governed by an MIT-style license that
|
||||
can be found in the LICENSE file at http://angular.io/license
|
||||
*/"><input type="hidden" name="files[app/toh/hero-list.component.html]" value="<h1>Tour of Heroes ({{mode}})</h1>
|
||||
<h3>Heroes:</h3>
|
||||
<ul>
|
||||
<li *ngFor="let hero of heroes">{{hero.name}}</li>
|
||||
</ul>
|
||||
|
||||
<label>New hero name: <input #newHeroName /></label>
|
||||
<button (click)="addHero(newHeroName.value); newHeroName.value=''">Add Hero</button>
|
||||
|
||||
<p class="error" *ngIf="errorMessage">{{errorMessage}}</p>
|
||||
|
||||
|
||||
<!--
|
||||
Copyright 2016 Google Inc. All Rights Reserved.
|
||||
Use of this source code is governed by an MIT-style license that
|
||||
can be found in the LICENSE file at http://angular.io/license
|
||||
-->"><input type="hidden" name="files[index.html]" value="<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Angular Http Demo</title>
|
||||
<script>document.write('<base href="' + document.location + '" />');</script>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
|
||||
<!-- Polyfills -->
|
||||
<script src="https://unpkg.com/core-js/client/shim.min.js"></script>
|
||||
|
||||
<script src="https://unpkg.com/zone.js@0.7.4?main=browser"></script>
|
||||
<script src="https://unpkg.com/systemjs@0.19.39/dist/system.src.js"></script>
|
||||
|
||||
<script src="https://cdn.rawgit.com/angular/angular.io/b3c65a9/public/docs/_examples/_boilerplate/systemjs.config.web.js"></script>
|
||||
<script>
|
||||
System.import('main.js').catch(function(err){ console.error(err); });
|
||||
</script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<my-app>Loading...</my-app>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
|
||||
|
||||
<!--
|
||||
Copyright 2016 Google Inc. All Rights Reserved.
|
||||
Use of this source code is governed by an MIT-style license that
|
||||
can be found in the LICENSE file at http://angular.io/license
|
||||
-->"><input type="hidden" name="files[app/heroes.json]" value="{
|
||||
"data": [
|
||||
{ "id": 1, "name": "Windstorm" },
|
||||
{ "id": 2, "name": "Bombasto" },
|
||||
{ "id": 3, "name": "Magneta" },
|
||||
{ "id": 4, "name": "Tornado" }
|
||||
]
|
||||
}
|
||||
"><input type="hidden" name="tags[0]" value="angular"><input type="hidden" name="tags[1]" value="example"><input type="hidden" name="tags[2]" value="http"><input type="hidden" name="tags[3]" value="jsonp"><input type="hidden" name="private" value="true"><input type="hidden" name="description" value="Angular Example - Http"></form><script>document.getElementById("mainForm").submit();</script></body></html>
|
@ -0,0 +1,13 @@
|
||||
// #docregion
|
||||
import { Component } from '@angular/core';
|
||||
|
||||
@Component({
|
||||
selector: 'my-app',
|
||||
template: `
|
||||
<hero-list></hero-list>
|
||||
<hero-list-promise></hero-list-promise>
|
||||
<my-wiki></my-wiki>
|
||||
<my-wiki-smart></my-wiki-smart>
|
||||
`
|
||||
})
|
||||
export class AppComponent { }
|
@ -0,0 +1,23 @@
|
||||
// #docregion
|
||||
import { NgModule } from '@angular/core';
|
||||
import { BrowserModule } from '@angular/platform-browser';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { HttpModule, JsonpModule } from '@angular/http';
|
||||
|
||||
import { AppComponent } from './app.component';
|
||||
|
||||
@NgModule({
|
||||
imports: [
|
||||
BrowserModule,
|
||||
FormsModule,
|
||||
HttpModule,
|
||||
JsonpModule
|
||||
],
|
||||
declarations: [ AppComponent ],
|
||||
bootstrap: [ AppComponent ]
|
||||
})
|
||||
export class AppModule {
|
||||
}
|
||||
|
||||
|
||||
|
@ -0,0 +1,46 @@
|
||||
// #docplaster
|
||||
// #docregion
|
||||
import { NgModule } from '@angular/core';
|
||||
import { BrowserModule } from '@angular/platform-browser';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { HttpModule, JsonpModule } from '@angular/http';
|
||||
|
||||
|
||||
import { InMemoryWebApiModule } from 'angular-in-memory-web-api';
|
||||
import { HeroData } from './hero-data';
|
||||
import { requestOptionsProvider } from './default-request-options.service';
|
||||
|
||||
import { AppComponent } from './app.component';
|
||||
|
||||
import { HeroListComponent } from './toh/hero-list.component';
|
||||
import { HeroListPromiseComponent } from './toh/hero-list.component.promise';
|
||||
|
||||
import { WikiComponent } from './wiki/wiki.component';
|
||||
import { WikiSmartComponent } from './wiki/wiki-smart.component';
|
||||
|
||||
@NgModule({
|
||||
imports: [
|
||||
BrowserModule,
|
||||
FormsModule,
|
||||
HttpModule,
|
||||
JsonpModule,
|
||||
// #docregion in-mem-web-api
|
||||
InMemoryWebApiModule.forRoot(HeroData)
|
||||
// #enddocregion in-mem-web-api
|
||||
],
|
||||
declarations: [
|
||||
AppComponent,
|
||||
HeroListComponent,
|
||||
HeroListPromiseComponent,
|
||||
WikiComponent,
|
||||
WikiSmartComponent
|
||||
],
|
||||
// #docregion provide-default-request-options
|
||||
providers: [ requestOptionsProvider ],
|
||||
// #enddocregion provide-default-request-options
|
||||
bootstrap: [ AppComponent ]
|
||||
})
|
||||
export class AppModule {}
|
||||
|
||||
|
||||
|
@ -0,0 +1,16 @@
|
||||
// #docregion
|
||||
import { Injectable } from '@angular/core';
|
||||
import { BaseRequestOptions, RequestOptions } from '@angular/http';
|
||||
|
||||
@Injectable()
|
||||
export class DefaultRequestOptions extends BaseRequestOptions {
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
// Set the default 'Content-Type' header
|
||||
this.headers.set('Content-Type', 'application/json');
|
||||
}
|
||||
}
|
||||
|
||||
export const requestOptionsProvider = { provide: RequestOptions, useClass: DefaultRequestOptions };
|
@ -0,0 +1,13 @@
|
||||
// #docregion
|
||||
import { InMemoryDbService } from 'angular-in-memory-web-api';
|
||||
export class HeroData implements InMemoryDbService {
|
||||
createDb() {
|
||||
let heroes = [
|
||||
{ id: 1, name: 'Windstorm' },
|
||||
{ id: 2, name: 'Bombasto' },
|
||||
{ id: 3, name: 'Magneta' },
|
||||
{ id: 4, name: 'Tornado' }
|
||||
];
|
||||
return {heroes};
|
||||
}
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
{
|
||||
"data": [
|
||||
{ "id": 1, "name": "Windstorm" },
|
||||
{ "id": 2, "name": "Bombasto" },
|
||||
{ "id": 3, "name": "Magneta" },
|
||||
{ "id": 4, "name": "Tornado" }
|
||||
]
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
<!-- #docregion -->
|
||||
<h1>Tour of Heroes ({{mode}})</h1>
|
||||
<h3>Heroes:</h3>
|
||||
<ul>
|
||||
<li *ngFor="let hero of heroes">{{hero.name}}</li>
|
||||
</ul>
|
||||
|
||||
<label>New hero name: <input #newHeroName /></label>
|
||||
<button (click)="addHero(newHeroName.value); newHeroName.value=''">Add Hero</button>
|
||||
|
||||
<p class="error" *ngIf="errorMessage">{{errorMessage}}</p>
|
@ -0,0 +1,41 @@
|
||||
// #docregion
|
||||
// Promise Version
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
import { Hero } from './hero';
|
||||
import { HeroService } from './hero.service.promise';
|
||||
|
||||
@Component({
|
||||
selector: 'hero-list-promise',
|
||||
moduleId: module.id,
|
||||
templateUrl: './hero-list.component.html',
|
||||
providers: [ HeroService ],
|
||||
styles: ['.error {color:red;}']
|
||||
})
|
||||
// #docregion component
|
||||
export class HeroListPromiseComponent implements OnInit {
|
||||
errorMessage: string;
|
||||
heroes: Hero[];
|
||||
mode = 'Promise';
|
||||
|
||||
constructor (private heroService: HeroService) {}
|
||||
|
||||
ngOnInit() { this.getHeroes(); }
|
||||
|
||||
// #docregion methods
|
||||
getHeroes() {
|
||||
this.heroService.getHeroes()
|
||||
.then(
|
||||
heroes => this.heroes = heroes,
|
||||
error => this.errorMessage = <any>error);
|
||||
}
|
||||
|
||||
addHero (name: string) {
|
||||
if (!name) { return; }
|
||||
this.heroService.addHero(name)
|
||||
.then(
|
||||
hero => this.heroes.push(hero),
|
||||
error => this.errorMessage = <any>error);
|
||||
}
|
||||
// #enddocregion methods
|
||||
}
|
||||
// #enddocregion component
|
@ -0,0 +1,45 @@
|
||||
// #docregion
|
||||
// Observable Version
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
import { Hero } from './hero';
|
||||
import { HeroService } from './hero.service';
|
||||
|
||||
@Component({
|
||||
moduleId: module.id,
|
||||
selector: 'hero-list',
|
||||
templateUrl: './hero-list.component.html',
|
||||
providers: [ HeroService ],
|
||||
styles: ['.error {color:red;}']
|
||||
})
|
||||
// #docregion component
|
||||
export class HeroListComponent implements OnInit {
|
||||
errorMessage: string;
|
||||
heroes: Hero[];
|
||||
mode = 'Observable';
|
||||
|
||||
constructor (private heroService: HeroService) {}
|
||||
|
||||
ngOnInit() { this.getHeroes(); }
|
||||
|
||||
// #docregion methods
|
||||
// #docregion getHeroes
|
||||
getHeroes() {
|
||||
this.heroService.getHeroes()
|
||||
.subscribe(
|
||||
heroes => this.heroes = heroes,
|
||||
error => this.errorMessage = <any>error);
|
||||
}
|
||||
// #enddocregion getHeroes
|
||||
|
||||
// #docregion addHero
|
||||
addHero (name: string) {
|
||||
if (!name) { return; }
|
||||
this.heroService.addHero(name)
|
||||
.subscribe(
|
||||
hero => this.heroes.push(hero),
|
||||
error => this.errorMessage = <any>error);
|
||||
}
|
||||
// #enddocregion addHero
|
||||
// #enddocregion methods
|
||||
}
|
||||
// #enddocregion component
|
@ -0,0 +1,60 @@
|
||||
// #docplaster
|
||||
// #docregion
|
||||
// Promise Version
|
||||
import { Injectable } from '@angular/core';
|
||||
import { Http, Response } from '@angular/http';
|
||||
import { Headers, RequestOptions } from '@angular/http';
|
||||
|
||||
// #docregion rxjs-imports
|
||||
import 'rxjs/add/operator/toPromise';
|
||||
// #enddocregion rxjs-imports
|
||||
|
||||
import { Hero } from './hero';
|
||||
|
||||
@Injectable()
|
||||
export class HeroService {
|
||||
// URL to web api
|
||||
private heroesUrl = 'app/heroes';
|
||||
|
||||
constructor (private http: Http) {}
|
||||
|
||||
// #docregion methods
|
||||
getHeroes (): Promise<Hero[]> {
|
||||
return this.http.get(this.heroesUrl)
|
||||
.toPromise()
|
||||
.then(this.extractData)
|
||||
.catch(this.handleError);
|
||||
}
|
||||
|
||||
addHero (name: string): Promise<Hero> {
|
||||
let headers = new Headers({ 'Content-Type': 'application/json' });
|
||||
let options = new RequestOptions({ headers: headers });
|
||||
|
||||
return this.http.post(this.heroesUrl, { name }, options)
|
||||
.toPromise()
|
||||
.then(this.extractData)
|
||||
.catch(this.handleError);
|
||||
}
|
||||
|
||||
private extractData(res: Response) {
|
||||
let body = res.json();
|
||||
return body.data || { };
|
||||
}
|
||||
|
||||
private handleError (error: Response | any) {
|
||||
// In a real world app, we might use a remote logging infrastructure
|
||||
let errMsg: string;
|
||||
if (error instanceof Response) {
|
||||
const body = error.json() || '';
|
||||
const err = body.error || JSON.stringify(body);
|
||||
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
|
||||
} else {
|
||||
errMsg = error.message ? error.message : error.toString();
|
||||
}
|
||||
console.error(errMsg);
|
||||
return Promise.reject(errMsg);
|
||||
}
|
||||
|
||||
// #enddocregion methods
|
||||
}
|
||||
// #enddocregion
|
@ -0,0 +1,80 @@
|
||||
// #docplaster
|
||||
// #docregion
|
||||
// Observable Version
|
||||
// #docregion v1
|
||||
import { Injectable } from '@angular/core';
|
||||
import { Http, Response } from '@angular/http';
|
||||
// #enddocregion v1
|
||||
// #docregion import-request-options
|
||||
import { Headers, RequestOptions } from '@angular/http';
|
||||
// #enddocregion import-request-options
|
||||
// #docregion v1
|
||||
|
||||
// #docregion rxjs-imports
|
||||
import { Observable } from 'rxjs/Observable';
|
||||
import 'rxjs/add/operator/catch';
|
||||
import 'rxjs/add/operator/map';
|
||||
// #enddocregion rxjs-imports
|
||||
|
||||
import { Hero } from './hero';
|
||||
|
||||
@Injectable()
|
||||
export class HeroService {
|
||||
// #docregion endpoint
|
||||
private heroesUrl = 'app/heroes'; // URL to web API
|
||||
// #enddocregion endpoint
|
||||
|
||||
// #docregion ctor
|
||||
constructor (private http: Http) {}
|
||||
// #enddocregion ctor
|
||||
|
||||
// #docregion methods, error-handling, http-get
|
||||
getHeroes (): Observable<Hero[]> {
|
||||
return this.http.get(this.heroesUrl)
|
||||
.map(this.extractData)
|
||||
.catch(this.handleError);
|
||||
}
|
||||
// #enddocregion error-handling, http-get, v1
|
||||
|
||||
// #docregion addhero, addhero-sig
|
||||
addHero (name: string): Observable<Hero> {
|
||||
// #enddocregion addhero-sig
|
||||
let headers = new Headers({ 'Content-Type': 'application/json' });
|
||||
let options = new RequestOptions({ headers: headers });
|
||||
|
||||
return this.http.post(this.heroesUrl, { name }, options)
|
||||
.map(this.extractData)
|
||||
.catch(this.handleError);
|
||||
}
|
||||
// #enddocregion addhero
|
||||
|
||||
// #docregion v1, extract-data
|
||||
private extractData(res: Response) {
|
||||
let body = res.json();
|
||||
return body.data || { };
|
||||
}
|
||||
// #enddocregion extract-data
|
||||
// #docregion error-handling
|
||||
|
||||
private handleError (error: Response | any) {
|
||||
// In a real world app, we might use a remote logging infrastructure
|
||||
let errMsg: string;
|
||||
if (error instanceof Response) {
|
||||
const body = error.json() || '';
|
||||
const err = body.error || JSON.stringify(body);
|
||||
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
|
||||
} else {
|
||||
errMsg = error.message ? error.message : error.toString();
|
||||
}
|
||||
console.error(errMsg);
|
||||
return Observable.throw(errMsg);
|
||||
}
|
||||
// #enddocregion error-handling, methods
|
||||
}
|
||||
// #enddocregion
|
||||
|
||||
/*
|
||||
// #docregion endpoint-json
|
||||
private heroesUrl = 'app/heroes.json'; // URL to JSON file
|
||||
// #enddocregion endpoint-json
|
||||
*/
|
@ -0,0 +1,6 @@
|
||||
// #docregion
|
||||
export class Hero {
|
||||
constructor(
|
||||
public id: number,
|
||||
public name: string) { }
|
||||
}
|
@ -0,0 +1,48 @@
|
||||
/* tslint:disable: member-ordering forin */
|
||||
// #docplaster
|
||||
// #docregion
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
|
||||
// #docregion rxjs-imports
|
||||
import { Observable } from 'rxjs/Observable';
|
||||
import 'rxjs/add/operator/debounceTime';
|
||||
import 'rxjs/add/operator/distinctUntilChanged';
|
||||
import 'rxjs/add/operator/switchMap';
|
||||
|
||||
// #docregion import-subject
|
||||
import { Subject } from 'rxjs/Subject';
|
||||
// #enddocregion import-subject
|
||||
|
||||
import { WikipediaService } from './wikipedia.service';
|
||||
|
||||
@Component({
|
||||
moduleId: module.id,
|
||||
selector: 'my-wiki-smart',
|
||||
template: `
|
||||
<h1>Smarter Wikipedia Demo</h1>
|
||||
<p>Search when typing stops</p>
|
||||
<input #term (keyup)="search(term.value)"/>
|
||||
<ul>
|
||||
<li *ngFor="let item of items | async">{{item}}</li>
|
||||
</ul>`,
|
||||
providers: [ WikipediaService ]
|
||||
})
|
||||
export class WikiSmartComponent implements OnInit {
|
||||
items: Observable<string[]>;
|
||||
|
||||
constructor (private wikipediaService: WikipediaService) {}
|
||||
|
||||
// #docregion subject
|
||||
private searchTermStream = new Subject<string>();
|
||||
search(term: string) { this.searchTermStream.next(term); }
|
||||
// #enddocregion subject
|
||||
|
||||
ngOnInit() {
|
||||
// #docregion observable-operators
|
||||
this.items = this.searchTermStream
|
||||
.debounceTime(300)
|
||||
.distinctUntilChanged()
|
||||
.switchMap((term: string) => this.wikipediaService.search(term));
|
||||
// #enddocregion observable-operators
|
||||
}
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
// #docregion
|
||||
import { Component } from '@angular/core';
|
||||
import { Observable } from 'rxjs/Observable';
|
||||
|
||||
import { WikipediaService } from './wikipedia.service';
|
||||
|
||||
@Component({
|
||||
selector: 'my-wiki',
|
||||
template: `
|
||||
<h1>Wikipedia Demo</h1>
|
||||
<p>Search after each keystroke</p>
|
||||
<input #term (keyup)="search(term.value)"/>
|
||||
<ul>
|
||||
<li *ngFor="let item of items | async">{{item}}</li>
|
||||
</ul>`,
|
||||
providers: [ WikipediaService ]
|
||||
})
|
||||
export class WikiComponent {
|
||||
items: Observable<string[]>;
|
||||
|
||||
constructor (private wikipediaService: WikipediaService) { }
|
||||
|
||||
search (term: string) {
|
||||
this.items = this.wikipediaService.search(term);
|
||||
}
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
// Create the query string by hand
|
||||
// #docregion
|
||||
import { Injectable } from '@angular/core';
|
||||
import { Jsonp } from '@angular/http';
|
||||
|
||||
import 'rxjs/add/operator/map';
|
||||
|
||||
@Injectable()
|
||||
export class WikipediaService {
|
||||
constructor(private jsonp: Jsonp) { }
|
||||
|
||||
// TODO: Add error handling
|
||||
search(term: string) {
|
||||
|
||||
let wikiUrl = 'http://en.wikipedia.org/w/api.php';
|
||||
|
||||
// #docregion query-string
|
||||
let queryString =
|
||||
`?search=${term}&action=opensearch&format=json&callback=JSONP_CALLBACK`;
|
||||
|
||||
return this.jsonp
|
||||
.get(wikiUrl + queryString)
|
||||
.map(response => <string[]> response.json()[1]);
|
||||
// #enddocregion query-string
|
||||
}
|
||||
}
|
@ -0,0 +1,30 @@
|
||||
// #docregion
|
||||
import { Injectable } from '@angular/core';
|
||||
import { Jsonp, URLSearchParams } from '@angular/http';
|
||||
|
||||
import 'rxjs/add/operator/map';
|
||||
|
||||
@Injectable()
|
||||
export class WikipediaService {
|
||||
constructor(private jsonp: Jsonp) {}
|
||||
|
||||
search (term: string) {
|
||||
|
||||
let wikiUrl = 'http://en.wikipedia.org/w/api.php';
|
||||
|
||||
// #docregion search-parameters
|
||||
let params = new URLSearchParams();
|
||||
params.set('search', term); // the user's search value
|
||||
params.set('action', 'opensearch');
|
||||
params.set('format', 'json');
|
||||
params.set('callback', 'JSONP_CALLBACK');
|
||||
// #enddocregion search-parameters
|
||||
|
||||
// #docregion call-jsonp
|
||||
// TODO: Add error handling
|
||||
return this.jsonp
|
||||
.get(wikiUrl, { search: params })
|
||||
.map(response => <string[]> response.json()[1]);
|
||||
// #enddocregion call-jsonp
|
||||
}
|
||||
}
|
27
aio/content/examples/server-communication/ts/src/index.html
Normal file
27
aio/content/examples/server-communication/ts/src/index.html
Normal file
@ -0,0 +1,27 @@
|
||||
<!DOCTYPE html>
|
||||
<!-- #docregion -->
|
||||
<html>
|
||||
<head>
|
||||
<title>Angular Http Demo</title>
|
||||
<base href="/">
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
|
||||
<!-- Polyfills -->
|
||||
<script src="node_modules/core-js/client/shim.min.js"></script>
|
||||
|
||||
<script src="node_modules/zone.js/dist/zone.js"></script>
|
||||
<script src="node_modules/systemjs/dist/system.src.js"></script>
|
||||
|
||||
<script src="systemjs.config.js"></script>
|
||||
<script>
|
||||
System.import('main.js').catch(function(err){ console.error(err); });
|
||||
</script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<my-app>Loading...</my-app>
|
||||
</body>
|
||||
|
||||
</html>
|
5
aio/content/examples/server-communication/ts/src/main.ts
Normal file
5
aio/content/examples/server-communication/ts/src/main.ts
Normal file
@ -0,0 +1,5 @@
|
||||
// #docregion
|
||||
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
|
||||
import { AppModule } from './app/app.module';
|
||||
|
||||
platformBrowserDynamic().bootstrapModule(AppModule);
|
Reference in New Issue
Block a user