目录

Aurelia - HTTP

在本章中,您将学习如何在Aurelia框架中处理HTTP请求。

第1步 - 创建视图

让我们创建四个按钮,用于向API发送请求。

app.html

<template>
   <button click.delegate = "getData()">GET</button>
   <button click.delegate = "postData()">POST</button>
   <button click.delegate = "updateData()">PUT</button>
   <button click.delegate = "deleteData()">DEL</button>
</template>

第2步 - 创建视图模型

为了向服务器发送请求,Aurelia建议fetch客户端。 我们正在为我们需要的每个请求创建函数(GET,POST,PUT和DELETE)。

import 'fetch';
import {HttpClient, json} from 'aurelia-fetch-client';
let httpClient = new HttpClient();
export class App {
   getData() {
      httpClient.fetch('http://jsonplaceholder.typicode.com/posts/1')
      .then(response => response.json())
      .then(data => {
         console.log(data);
      });
   }
   myPostData = { 
      id: 101
   }
	postData(myPostData) {
      httpClient.fetch('http://jsonplaceholder.typicode.com/posts', {
         method: "POST",
         body: JSON.stringify(myPostData)
      })
      .then(response => response.json())
      .then(data => {
         console.log(data);
      });
   }
   myUpdateData = {
      id: 1
   }
	updateData(myUpdateData) {
      httpClient.fetch('http://jsonplaceholder.typicode.com/posts/1', {
         method: "PUT",
         body: JSON.stringify(myUpdateData)
      })
      .then(response => response.json())
      .then(data => {
         console.log(data);
      });
   }
   deleteData() {
      httpClient.fetch('http://jsonplaceholder.typicode.com/posts/1', {
         method: "DELETE"
      })
      .then(response => response.json())
      .then(data => {
         console.log(data);
      });
   }
}

我们可以运行应用程序并分别单击GETPOSTPUTDEL按钮。 我们可以在控制台中看到每个请求都成功,并记录结果。

Aurelia HTTP示例
<上一篇.Aurelia - Forms
Aurelia - Refs.下一篇>
↑回到顶部↑
WIKI教程 @2018