Dart Example

Just another WordPress site

AngularDart v4 Http Get

AngularDart v4 Sample Code,Demo
  • AngularDart : 4.0.0
  • Dart : 1.24.1
Loading…
(html)
<head>
.....
  <script defer src="main.dart" type="application/dart"></script>
  <script defer src="packages/browser/dart.js"></script>
</head>
<body>
  <my-app>Loading...</my-app>
</body>

(pubspec.yaml)
.....
environment:
  sdk: '>=1.24.0 <2.0.0'
dependencies:
  angular: ^4.0.0
  angular_forms: ^1.0.0
  angular_router: ^1.0.2
  http: ^0.11.0
  stream_transform: ^0.0.6

dev_dependencies:
  angular_test: ^1.0.0
  browser: ^0.10.0
  dart_to_js_script_rewriter: ^1.0.1
  mockito: ^2.0.2
  test: ^0.12.21

transformers:
- angular:
    entry_points:
    - web/main.dart
    - test/**_test.dart
- test/pub_serve:
    $include: test/**_test.dart
- dart_to_js_script_rewriter
(main.dart)
import 'dart:async';
import 'dart:convert';

import 'package:angular/angular.dart';
import 'package:http/browser_client.dart';

import 'http_service.dart';

class Friend {
  int id;
  String name;
  int age;
  String address;

  Friend(this.id,this.name,this.age,this.address);
}

@Component(
    selector: 'my-app',
    template: '''
    <ul>
      <li *ngFor="let friend of friends">
        <span class="badge badge-default">{{friend.id}}</span> {{friend.name}}
      </li>
    </ul>
    <button (click)="get1(true)">Http Get</button>
    <button (click)="get1(false)">Http Get Error</button><br />
    <div *ngIf="show">
      <strong>Http Response Data</strong><br />
      <table class="table table-striped">
        <thead><tr>
          <th>№</th><th>Name</th><th>Age</th><th>Address</th>
        </tr></thead>
        <tbody>
          <tr *ngFor="let item of friends1">
            <td>{{item.id}}</td>
            <td>{{item.name}}</td>
            <td>{{item.age}}</td>
            <td>{{item.address}}</td>
          </tr>
        </tbody>
      </table>
    </div>
    <div *ngIf="!show">
      <strong>HTTP Error</strong><br />
      <span>Status Code: {{status}}</span><br />
      <span>Error Comment: {{error}}</span><br />
    </div>
    ''',
    directives: const [CORE_DIRECTIVES],
    providers: const [HttpService]
)
class AppComponent implements OnInit {
  String error;
  int status;
  bool show = false;
  List<Friend> friends;
  List<Friend> friends1;
  HttpService _httpService;
  String _url = "json/friends.json";
  AppComponent(this._httpService);

  Future<Null> get(String url) async {
    friends = await _httpService.get(url);
  }
  void ngOnInit() {
    get(_url);
  }
  void get1(bool tf) async {
    show = tf;
    var client = new BrowserClient();
    if (tf) {
      await client.get('json/friends.json')
      .then((response) {
        friends1 = JSON.decode(response.body)['data']
        .map((value) => new Friend(value['id'], value['name'],value['age'],value['address']))
        .toList();
      })
      .catchError((e) {
        error = e;
      });
    } else {
      await client.get('invalid-url')
      .then((response) {
        status = response.statusCode;
        error = response.body.substring(50,100);
      })
      .catchError((e) {
        error = e;
      });
    }
  }
}

void main() {
  bootstrap(AppComponent, [provide(BrowserClient, useFactory: () => new BrowserClient(), deps: [])]
  );
}


(http_service.dart)
import 'dart:async';
import 'dart:convert';

import 'package:angular/angular.dart';
import 'package:http/browser_client.dart';

class Friend {
  int id;
  String name;
  int age;
  String address;

  Friend(this.id,this.name,this.age,this.address);
}

@Injectable()
class HttpService {
  BrowserClient _http;
  HttpService(this._http);

  Future<List<Friend>> get(String url) async {
    try {
      final response = await _http.get(url);
      List<Friend> friends = JSON.decode(response.body)['data']
          .map((value) => new Friend(value['id'], value['name'],value['age'],value['address']))
          .toList();
      return friends;
    } catch (e) {
      throw _handleError(e);
    }
  }

  Exception _handleError(dynamic e) {
    print(e); // for demo purposes only
    return new Exception('Server error; cause: $e');
  }

}

(friends.json)
{
   "data": [
  {"id": 1, "name": "John", "age": 20, "address": "1st Ave Seattle WA"},
  {"id": 2, "name": "Jessie", "age": 55, "address": "2nd Ave Seattle WA"},
  {"id": 3, "name": "Peter", "age": 20, "address": "Mercer St Seattle WA"},
  {"id": 4, "name": "Erika", "age": 37, "address": "Alaskan Way Seattle WA"}
    ]
}