Dart Example

AngularDart v4 Http Get

AngularDart v4 Sample Code,Demo
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 
    
(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"}
    ]
}
Exit mobile version