docs(server-communication/dart): add sample

closes #829
This commit is contained in:
Adão Júnior 2016-02-10 17:27:14 -02:00 committed by Kathy Walrath
parent c3ce451637
commit 240b0a2f70
12 changed files with 303 additions and 0 deletions

View File

@ -0,0 +1,10 @@
import 'package:http_in_memory_web_api/http_in_memory_web_api.dart';
CreateDb heroData = () => {
'heroes': [
{"id": "1", "name": "Windstorm"},
{"id": "2", "name": "Bombasto"},
{"id": "3", "name": "Magneta"},
{"id": "4", "name": "Tornado"}
]
};

View File

@ -0,0 +1,15 @@
// #docregion
class Hero {
final int id;
final String name;
Hero(this.id, this.name);
factory Hero.fromJson(Map hero) {
final _id = hero['id'];
final id = _id is int ? _id : int.parse(_id);
return new Hero(id,hero['name']);
}
Map toJson() => {'id': id, 'name': name};
}

View File

@ -0,0 +1,58 @@
// #docregion
import 'dart:async';
import 'package:angular2/angular2.dart';
import 'hero.dart';
import 'hero_service.dart';
@Component(
selector: 'hero-list',
// #docregion template
template: '''
<h3>Heroes:</h3>
<ul>
<li *ngFor="#hero of heroes">
{{hero.name}}
</li>
</ul>
New Hero:
<input #newHero />
<button (click)="addHero(newHero.value); newHero.value=''">
Add Hero
</button>
<div class="error" *ngIf="hasErrorMessage">{{errorMessage}}</div>
''',
// #enddocregion template
styles: const ['.error {color:red;}'])
// #docregion component
class HeroListComponent implements OnInit {
final HeroService _heroService;
String errorMessage;
List<Hero> heroes = [];
HeroListComponent(this._heroService);
bool get hasErrorMessage => errorMessage != null;
Future ngOnInit() => getHeroes();
// #docregion methods
Future getHeroes() async {
try {
heroes = await _heroService.getHeroes();
} catch (e) {
errorMessage = e.toString();
}
}
Future addHero(String name) async {
name = name.trim();
if (name.isEmpty) return;
try {
heroes.add(await _heroService.addHero(name));
} catch (e) {
errorMessage = e.toString();
}
}
// #enddocregion methods
}
// #enddocregion component

View File

@ -0,0 +1,41 @@
// #docplaster
// #docregion
import 'dart:async';
import 'dart:convert';
import 'package:angular2/angular2.dart';
// #enddocregion v1
// #docregion import-request-options
import 'package:http/browser_client.dart';
// #enddocregion import-request-options
// #docregion v1
import 'hero.dart';
@Injectable()
class HeroService {
final String _heroesUrl = 'app/heroes';
BrowserClient _http;
HeroService(this._http);
// #docregion methods
Future<List<Hero>> getHeroes() async {
final response = await _http.get(_heroesUrl);
final heroes = JSON
.decode(response.body)['data']
.map((value) => new Hero.fromJson(value))
.toList();
print(JSON.encode(heroes)); // eyeball results in the console
return heroes;
}
Future<Hero> addHero(String name) async {
final headers = {'content-type': 'application/json'};
final body = JSON.encode({'name': name});
final response = await _http.post(_heroesUrl, headers: headers, body: body);
return new Hero.fromJson(JSON.decode(response.body));
}
// #enddocregion methods
}
// #enddocregion

View File

@ -0,0 +1,35 @@
import 'package:angular2/angular2.dart';
import 'package:http_in_memory_web_api/http_in_memory_web_api.dart';
import 'package:http/browser_client.dart';
import 'package:server_communication/hero_data.dart';
import 'hero_list_component.dart';
import 'hero_service.dart';
@Injectable()
HttpClientInMemoryBackendService HttpClientInMemoryBackendServiceFactory() =>
new HttpClientInMemoryBackendService(heroData); // in-mem server
@Component(
selector: 'my-toh',
// #docregion template
template: '''
<h1>Tour of Heroes</h1>
<hero-list></hero-list>
''',
// #enddocregion template
providers: const [
HeroService,
//#enddocregion
//#docregion in-mem-web-api-providers
// in-memory web api providers
const Provider(BrowserClient,
useFactory: HttpClientInMemoryBackendServiceFactory)
//#enddocregion in-mem-web-api-providers
//#docregion
],
directives: const [
HeroListComponent
])
class TohComponent {}
// #enddocregion

View File

@ -0,0 +1,26 @@
// #docregion
import 'dart:async';
import 'package:angular2/angular2.dart';
import 'wikipedia_service.dart';
@Component(
selector: 'my-wiki',
template: '''
<h1>Wikipedia Demo</h1>
<p><i>Fetches after each keystroke</i></p>
<input #term (keyup)="search(term.value)"/>
<ul>
<li *ngFor="#item of items">{{item}}</li>
</ul>
''',
providers: const [WikipediaService])
class WikiComponent {
final WikipediaService _wikipediaService;
List items = [];
WikiComponent(this._wikipediaService);
Future search(String term) async {
items = await this._wikipediaService.search(term);
}
}

View File

@ -0,0 +1,37 @@
// #docregion
import 'package:angular2/angular2.dart';
import 'package:stream_transformers/stream_transformers.dart';
import 'wikipedia_service.dart';
@Component(
selector: 'my-wiki-smart',
template: '''
<h1>Smarter Wikipedia Demo</h1>
<p><i>Fetches when typing stops</i></p>
<input #term (keyup)="search(term.value)"/>
<ul>
<li *ngFor="#item of items">{{item}}</li>
</ul>
''',
providers: const [WikipediaService])
class WikiSmartComponent {
final WikipediaService _wikipediaService;
List items = [];
WikiSmartComponent(this._wikipediaService) {
_searchTermStream
.transform(new Debounce(new Duration(milliseconds: 300)))
.distinct()
.transform(new FlatMapLatest(
(term) => _wikipediaService.search(term).asStream()))
.forEach((data) {
items = data;
});
}
final EventEmitter _searchTermStream = new EventEmitter();
void search(String term) => _searchTermStream.add(term);
}

View File

@ -0,0 +1,24 @@
// #docregion
import 'dart:async';
import 'package:angular2/angular2.dart';
import 'package:jsonpadding/jsonpadding.dart';
@Injectable()
class WikipediaService {
Future<List<String>> search(String term) async {
// #docregion call-jsonp
Uri uri = new Uri(
scheme: 'http',
host: 'en.wikipedia.org',
path: 'w/api.php',
queryParameters: {
'search': term,
'action': 'opensearch',
'format': 'json'
});
// TODO: Error handling
List result = await jsonp(uri);
return result[1];
// #enddocregion call-jsonp
}
}

View File

@ -0,0 +1,20 @@
# #docregion
name: server_communication
description: Server Communication
version: 0.0.1
environment:
sdk: '>=1.13.0 <2.0.0'
dependencies:
angular2: 2.0.0-beta.6
browser: ^0.10.0
dart_to_js_script_rewriter: ^0.1.0
http: ^0.11.3+3
jsonpadding: ^0.1.0
stream_transformers: ^0.3.0+3
http_in_memory_web_api: ^0.0.1
transformers:
- angular2:
platform_directives: 'package:angular2/common.dart#CORE_DIRECTIVES'
platform_pipes: 'package:angular2/common.dart#COMMON_PIPES'
entry_points: 'web/main.dart'
- dart_to_js_script_rewriter

View File

@ -0,0 +1,8 @@
{
"data": [
{ "id": "1", "name": "Windstorm" },
{ "id": "2", "name": "Bombasto" },
{ "id": "3", "name": "Magneta" },
{ "id": "4", "name": "Tornado" }
]
}

View File

@ -0,0 +1,18 @@
<!DOCTYPE html>
<!-- #docregion -->
<html>
<head>
<title>Angular 2 Http Demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script defer src="main.dart" type="application/dart"></script>
<script defer src="packages/browser/dart.js"></script>
</head>
<body>
<my-toh>ToH Loading...</my-toh>
<my-wiki>Wiki Loading...</my-wiki>
<my-wiki-smart>WikiSmart loading...</my-wiki-smart>
</body>
</html>

View File

@ -0,0 +1,11 @@
// #docregion
import 'package:angular2/bootstrap.dart';
import 'package:server_communication/toh/toh_component.dart';
import 'package:server_communication/wiki/wiki_component.dart';
import 'package:server_communication/wiki/wiki_smart_component.dart';
main() {
bootstrap(TohComponent);
bootstrap(WikiComponent);
bootstrap(WikiSmartComponent);
}