Dart Example

AngularDart v4 Http Post

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 
    
import 'dart:async';
import 'dart:convert';

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

@Component(
    selector: 'my-app',
    template: '''
    <span>Sending Data</span><br />
    <span>{{send_data|json}}</span><br />
    <strong>'Content-Type': 'application/json'</strong><br />
    <button (click)="postCall(true)">Send</button><br />
    <strong>'application/x-www-form-urlencoded'</strong><br />
    <button (click)="postCall(false)">Send</button><br />
    <span>Response Data: {{data}}</span><br />
    <span>Status Code: {{status}}</span><br />
    ''',
    directives: const [CORE_DIRECTIVES],
    pipes: const [COMMON_PIPES]
)
class AppComponent {
  var client = new BrowserClient();
  String data;
  int status;
  String error;
  Map _headers;
  Map send_data = {
    "id": "0101",
    "name": "Tom"
  };
  String trans_data;
  String _url = "lamp-http_server.php";
  void postCall (bool tf) async {
    if (tf) {
      _headers = {'Content-Type': 'application/json'};
      client.post(_url, headers: _headers, body: JSON.encode(send_data))
      .then((response) {
        data = response.body;
        status = response.statusCode;
      })
      .catchError((e) {
        error = e;
      });
    } else {
      _headers = {'Content-Type': 'application/x-www-form-urlencoded'};
      send_data.forEach((k, v) {
        if (trans_data != null) {
          trans_data += '&' + k + '=' + v;
        } else {
          trans_data = k + '=' + v;
        }
      });
      client.post(_url, headers: _headers, body: trans_data)
      .then((response) {
        data = response.body;
        status = response.statusCode;
      })
      .catchError((e) {
        error = e;
      });
    }
  }
}

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