JSON : Placeholder

JSON : Placeholder (https://jsonplaceholder.typicode.com/) 是一个用于测试的 REST API 网站。

以下使用 RxJS6 + React.js 调用该网站的 REST API,获取字符串以及 JSON 数据。

  • GET /posts/1
  • GET /posts
  • POST /posts
  • PUT /posts/1
  • DELETE /posts/1

所有 GET API 都返回JSON数据,格式(JSON-Schema)如下:

{
"type":"object",
"properties": {
"userId": {"type" : "integer"},
"id": {"type" : "integer"},
"title": {"type" : "string"},
"body": {"type" : "string"}
}
}

创建工程

# 安装 CLI
$ npm install -g create-react-app
# 创建新的应用程序 RxExample
$ create-react-app rx-example --scripts-version=react-scripts-ts
$ cd rx-example
$ npm start

打开 Intellij IDEA, File / New / Project From Existing Sources...,然后选中工程所在文件夹

在向导的第1页选择 Create project from existing sources

完成向导后在点击 Finish 创建工程。

点击 Add Configurations, 点击 +npm

Name: React CLI Server

Scripts: start

点击 OK 完成配置。

点击 React CLI Server 启动程序。

http://localhost:3000/ 可打开网页。

TSLint

打开 tslint.json,将其改为

{
"extends": ["tslint:recommended", "tslint-react", "tslint-config-prettier"],
"linterOptions": {
"exclude": [
"config/**/*.js",
"node_modules/**/*.ts",
"coverage/lcov-report/*.js"
]
},
"rules": {
"interface-name": false,
"ordered-imports": false,
"no-console": false,
"object-literal-sort-keys": false,
"member-access": false,
"variable-name": false,
"member-ordering": false,
"class-name": false
}
}

Post

在 src 文件夹下添加 post.ts,内容如下

export class Post {
userId!: number;
id!: number;
title!: string;
body!: string;
toString(): string {
return `Post {userId = ${this.userId}, id = ${this.id}, title = "${this.title}", body = "${this.body.replace(/\n/g, '\\n')}"}`;
}
}

安装 react.di

react.di 是一个在 React.js 中实现 DI(依赖注入) 的包。

使用这个包需要安装 react.di 和 reflect-metadata。

$ npm install react.di@next reflect-metadata --save

打开 tsconfig.json 在 compilerOptions 中

添加关于 emitDecoratorMetadata 的设定。

    "emitDecoratorMetadata": true,
"experimentalDecorators": true,

安装 Rxios

访问 API 采用将 RxJS 和 axios 合为一体的 Rxios 组件,但是该组件尚未升级到 RxJS6。

这里我们只安装 RxJS 和 axios,然后直接以源码形式引入 Rxios,并将其升级到 RxJS6。

$ npm install axios rxjs

在 src 文件夹下添加 rxios.ts,内容如下

// https://github.com/davguij/rxios/blob/master/src/index.ts
// ported to rxjs6 import axios, { AxiosInstance, AxiosRequestConfig, AxiosPromise } from 'axios';
// import { Observable } from 'rxjs/Observable';
import { Observable } from 'rxjs'; export interface rxiosConfig extends AxiosRequestConfig {
localCache?: boolean;
} class rxios {
private _httpClient: AxiosInstance; constructor(options: rxiosConfig = {}) {
this._httpClient = axios.create(options);
} private _makeRequest<T>(method: string, url: string, queryParams?: object, body?: object) {
let request: AxiosPromise<T>;
switch (method) {
case 'GET':
request = this._httpClient.get<T>(url, {params: queryParams});
break;
case 'POST':
request = this._httpClient.post<T>(url, body, {params: queryParams});
break;
case 'PUT':
request = this._httpClient.put<T>(url, body, {params: queryParams});
break;
case 'PATCH':
request = this._httpClient.patch<T>(url, body, {params: queryParams});
break;
case 'DELETE':
request = this._httpClient.delete(url, {params: queryParams});
break; default:
throw new Error('Method not supported');
}
return new Observable<T>(subscriber => {
request.then(response => {
subscriber.next(response.data);
subscriber.complete();
}).catch((err: Error) => {
subscriber.error(err);
subscriber.complete();
});
});
} public get<T>(url: string, queryParams?: object) {
return this._makeRequest<T>('GET', url, queryParams);
} public post<T>(url: string, body: object, queryParams?: object) {
return this._makeRequest<T>('POST', url, queryParams, body);
} public put<T>(url: string, body: object, queryParams?: object) {
return this._makeRequest<T>('PUT', url, queryParams, body);
} public patch<T>(url: string, body: object, queryParams?: object) {
return this._makeRequest<T>('PATCH', url, queryParams, body);
} public delete(url: string, queryParams?: object) {
return this._makeRequest('DELETE', url, queryParams);
}
} export {rxios, rxios as Rxios};

post 服务

在 src 文件夹下添加 post.service.ts,内容如下

import { Injectable } from 'react.di';
import { Observable, from } from 'rxjs';
import { map, mergeAll, take, tap } from 'rxjs/operators';
import { Post } from './post';
import { Rxios } from './rxios'; @Injectable
export class PostService {
private readonly http = new Rxios();
private readonly baseUrl = 'http://jsonplaceholder.typicode.com/'; constructor() {
this.getPostAsString().subscribe();
this.getPostAsJson().subscribe();
this.getPosts(2).subscribe();
this.createPost().subscribe();
this.updatePost().subscribe();
this.deletePost().subscribe();
} private getPostAsString(): Observable<string> {
const url = `${this.baseUrl}posts/1`;
return new Rxios({transformResponse: undefined}).get<string>(url)
.pipe(
tap((result: any) => console.log(result)),
);
} private getPostAsJson(): Observable<Post> {
const url = `${this.baseUrl}posts/1`;
return this.http.get<Post>(url)
.pipe(
map((result: any) => Object.assign(new Post(), result)),
tap((result: any) => console.log('' + result)),
);
} private getPosts(n: number): Observable<Post> {
const url = `${this.baseUrl}posts`;
return from(this.http.get<Post[]>(url))
.pipe(
mergeAll(),
map((result: any) => Object.assign(new Post(), result)),
take(n),
tap((result: any) => console.log('' + result)),
);
} private createPost(): Observable<string> {
const url = `${this.baseUrl}posts`;
return this.http.post(url, {
params: {
userId: 101,
title: 'test title',
body: 'test body',
}
})
.pipe(
map((result: any) => JSON.stringify(result)),
tap((result: any) => console.log(result)),
);
} private updatePost(): Observable<string> {
const url = `${this.baseUrl}posts/1`;
return this.http.put(url, {
params: {
userId: 101,
title: 'test title',
body: 'test body',
}
})
.pipe(
map((result: any) => JSON.stringify(result)),
tap((result: any) => console.log(result)),
);
} private deletePost(): Observable<string> {
const url = `${this.baseUrl}posts/1`;
return this.http.delete(url)
.pipe(
map((result: any) => JSON.stringify(result)),
tap((result: any) => console.log(result)),
);
}
}
  • getPostAsString 方法取出第1个Post,返回字符串
  • getPostAsJson 方法取出第1个Post,返回Post对象
  • getPosts 方法取出前n个Post,返回n个Post对象
  • createPost 方法创建1个Post,返回字符串
  • updatePost 方法更新第1个Post,返回字符串
  • deletePost 方法删除第1个Post,返回字符串

打开 App.tsx,将其改为

import * as React from 'react';
import './App.css'; import logo from './logo.svg';
import { PostService } from './post.service';
import { Inject, Module } from 'react.di'; @Module({
providers: [
PostService,
],
})
class App extends React.Component {
@Inject postService!: PostService; componentDidMount() {
console.log(this.postService);
} public render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.tsx</code> and save to reload.
</p>
</div>
);
}
} export default App;

输出结果

{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
Post {userId = 1, id = 1, title = "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", body = "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"}
Post {userId = 1, id = 1, title = "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", body = "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"}
Post {userId = 1, id = 2, title = "qui est esse", body = "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"}
{"params":{"userId":101,"title":"test title","body":"test body"},"id":101}
{"params":{"userId":101,"title":"test title","body":"test body"},"id":1}
{}

ReactiveX 学习笔记(26)使用 RxJS + React.js 调用 REST API的更多相关文章

  1. ReactiveX 学习笔记(25)使用 RxJS + Vue.js 调用 REST API

    JSON : Placeholder JSON : Placeholder (https://jsonplaceholder.typicode.com/) 是一个用于测试的 REST API 网站. ...

  2. ReactiveX 学习笔记(0)学习资源

    ReactiveX 学习笔记 ReactiveX 学习笔记(1) ReactiveX 学习笔记(2)创建数据流 ReactiveX 学习笔记(3)转换数据流 ReactiveX 学习笔记(4)过滤数据 ...

  3. Dynamic CRM 2013学习笔记(九)CrmFetchKit.js介绍:Fetchxml、多表联合查询, 批量更新

    CrmFetchKit.js是一个跨浏览器的一个类库,允许通过JavaScript来执行fetch xml的查询,还可以实现批量更新,分页查询等.目前已支持Chrome 25, Firefox 19 ...

  4. [原创]java WEB学习笔记26:MVC案例完整实践(part 7)---修改的设计和实现

    本博客为原创:综合 尚硅谷(http://www.atguigu.com)的系统教程(深表感谢)和 网络上的现有资源(博客,文档,图书等),资源的出处我会标明 本博客的目的:①总结自己的学习过程,相当 ...

  5. React学习笔记-1-什么是react,react环境搭建以及第一个react实例

    什么是react?react的官方网站:https://facebook.github.io/react/下图这个就是就是react的标志,非常巧合的是他和我们的github的编辑器Atom非常相似. ...

  6. Nodejs学习笔记(六)--- Node.js + Express 构建网站预备知识

    目录 前言 新建express项目并自定义路由规则 如何提取页面中的公共部分? 如何提交表单并接收参数? GET 方式 POST 方式 如何字符串加密? 如何使用session? 如何使用cookie ...

  7. Nodejs学习笔记(六)—Node.js + Express 构建网站预备知识

    前言 前面经过五篇Node.js的学习,基本可以开始动手构建一个网站应用了,先用这一篇了解一些构建网站的知识! 主要是些基础的东西... 如何去创建路由规则.如何去提交表单并接收表单项的值.如何去给密 ...

  8. 【React】学习笔记(一)——React入门、面向组件编程、函数柯里化

    课程原视频:https://www.bilibili.com/video/BV1wy4y1D7JT?p=2&spm_id_from=pageDriver 目录 一.React 概述 1.1.R ...

  9. ‎Cocos2d-x 学习笔记(26) 从源码学习 DrawCall 的降低方法

    [Cocos2d-x]学习笔记目录 本文链接:https://www.cnblogs.com/deepcho/cocos2dx-drawcall-glcalls 1. 屏幕左下角 我们通常在Cocos ...

随机推荐

  1. Podman and Buildah for Docker users

    转自:https://developers.redhat.com/blog/2019/02/21/podman-and-buildah-for-docker-users/ I was asked re ...

  2. js设置,获取cookie

    function setCookie(c_name,value,expireMinutes){ var exdate=new Date(); exdate.setMinutes(exdate.getM ...

  3. oracle报错 ORA-02290: 违反检查约束条件问题

    场景: 使用plsql/developer 将原本要求非空的字段   改为可以为空 然后在插入数据的时候 报错改字段约束条件还起作用 解决方案: 首先查询该表的约束条件 select * from u ...

  4. Ansible 批量修改密码

    客户要求每3个月修改一次主机密码.密码规则为客服提供的一串字符 xxxx + 主机后3位. 将需要登录主机添加到 Ansible. 将需要登录主机的公钥添加到 known_hosts ssh-keys ...

  5. centos7配置iscsi

    什么是ISCSI iscsi--internet small computer system interface互联小型计算机系统接口,将数据包封装在TCP/IP协议中传输,使用普通网线和网络设备即可 ...

  6. Spring Boot - AOP(面向切面)

    AOP 全称 Aspect Oriented Programming(面向切面),AOP主要实现的目的是针对业务处理过程中的切面进行提取,它所面对的是处理过程中的某个步骤或阶段,以获得逻辑过程中各部分 ...

  7. python爬虫---selenium库的用法

    python爬虫---selenium库的用法 selenium是一个自动化测试工具,支持Firefox,Chrome等众多浏览器 在爬虫中的应用主要是用来解决JS渲染的问题. 1.使用前需要安装这个 ...

  8. 小梵同学 GO!

    刘德翠 1. Vue.js实战读书笔记(1) 2.Vue.js实战读书笔记--计算属性 3. Vue.js实战读书笔记--v-bind及class与style绑定 4. Vue.js实战读书笔记--内 ...

  9. codechef February Challenge 2018 简要题解

    比赛链接:https://www.codechef.com/FEB18,题面和提交记录是公开的,这里就不再贴了 Chef And His Characters 模拟题 Chef And The Pat ...

  10. 知识点总结——STL相关(持续补充)

    ---恢复内容开始--- C++ STL 与ACM竞赛相关的应用 1.vector vector是动态数组,可以理解为是能够根据需要随时申请内存的动态数组. 常用操作如下: 容量 vec.size() ...