JSON : Placeholder

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

以下使用 RxJS6 + Angular 6 调用该网站的 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"}
}
}

创建工程

# 安装 Angular CLI
$ npm install -g @angular/cli
# 创建新的应用程序 RxExample
$ ng new RxExample
$ cd RxExample
$ npm audit fix --force

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

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

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

点击 Add Configurations, 点击 +npm

Name: Angular CLI Server

Scripts: start

点击 OK 完成配置。

点击 Angular CLI Server 启动程序。

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

Post

在 app 文件夹下添加 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')}"}`;
}
}

post 服务

# 添加 post 服务
$ ng generate service post

将生成的 post.service.ts 改为

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, from } from 'rxjs';
import { map, mergeAll, take, tap } from 'rxjs/operators';
import { Post } from './post'; @Injectable()
export class PostService {
private baseUrl = 'http://jsonplaceholder.typicode.com/'; constructor(private http: HttpClient) { } restExample() {
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 this.http.get(url, {responseType: 'text'})
.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.module.ts 中添加 PostService 和 HttpClientModule 的引用。

import { PostService } from './post.service';
import { HttpClientModule } from '@angular/common/http'; @NgModule({
imports: [
BrowserModule,
HttpClientModule,
],
providers: [
PostService,
],
})

在 app.component.ts 中添加 post 服务的引用,将其改为

import { Component } from '@angular/core';
import {PostService} from './post.service'; @Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'RxExample';
constructor(private postService: PostService) { }
}

输出结果

{
"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"}
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"}
{"params":{"userId":101,"title":"test title","body":"test body"},"id":1}
{"params":{"userId":101,"title":"test title","body":"test body"},"id":101}
{}

ReactiveX 学习笔记(18)使用 RxJS + Angular 调用 REST API的更多相关文章

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

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

  2. springmvc学习笔记(18)-json数据交互

    springmvc学习笔记(18)-json数据交互 标签: springmvc springmvc学习笔记18-json数据交互 springmvc进行json交互 环境准备 加入json转换的依赖 ...

  3. Ext.Net学习笔记18:Ext.Net 可编辑的GridPanel

    Ext.Net学习笔记18:Ext.Net 可编辑的GridPanel Ext.Net GridPanel 有两种编辑模式:编辑单元格和编辑行. 单元格编辑: 行编辑: 可以看出,单元格编辑的时候,只 ...

  4. Memcached 学习笔记(二)——ruby调用

    Memcached 学习笔记(二)——ruby调用 上一节我们讲述了怎样安装memcached及memcached常用命令.这一节我们将通过ruby来调用memcached相关操作. 第一步,安装ru ...

  5. SQL反模式学习笔记18 减少SQL查询数据,避免使用一条SQL语句解决复杂问题

    目标:减少SQL查询数据,避免使用一条SQL语句解决复杂问题 反模式:视图使用一步操作,单个SQL语句解决复杂问题 使用一个查询来获得所有结果的最常见后果就是产生了一个笛卡尔积.导致查询性能降低. 如 ...

  6. golang学习笔记18 用go语言编写移动端sdk和app开发gomobile

    golang学习笔记18 用go语言编写移动端sdk和app开发gomobile gomobile的使用-用go语言编写移动端sdk和app开发https://blog.csdn.net/u01249 ...

  7. python3.4学习笔记(二十五) Python 调用mysql redis实例代码

    python3.4学习笔记(二十五) Python 调用mysql redis实例代码 #coding: utf-8 __author__ = 'zdz8207' #python2.7 import ...

  8. Hadoop源码学习笔记(4) ——Socket到RPC调用

    Hadoop源码学习笔记(4) ——Socket到RPC调用 Hadoop是一个分布式程序,分布在多台机器上运行,事必会涉及到网络编程.那这里如何让网络编程变得简单.透明的呢? 网络编程中,首先我们要 ...

  9. cocos2d-x学习笔记(18)--游戏打包(windows平台)

    cocos2d-x学习笔记(18)--游戏打包(windows平台)           之前做好的游戏,都是在vs2008下编译执行的.假设说想把游戏公布到网上或者和其它人一起分享游戏,那就得对游戏 ...

随机推荐

  1. centos 7 修改host文件

    centos7与之前的版本都不一样,修改主机名在/ect/hostname 和/ect/hosts 这两个文件控制 首先修改/etc/hostname vi /etc/hostname 打开之后的内容 ...

  2. 0001 - Spring 框架和 Tomcat 容器扩展接口揭秘

    前言 在 Spring 框架中,每个应用程序上下文(ApplicationContext)管理着一个 BeanFactory,BeanFactory 主要负责 Bean 定义的保存.Bean 的创建. ...

  3. Linux IO多路复用 select/poll/epoll

    Select -- synchronius I/O multiplexing select, FS_SET,FD_CLR,FD_ISSET,FD_ZERO #include <sys/time. ...

  4. 互斥锁,IPC队列

    进程同步(锁) 进程之间数据不共享,但是共享同一套文件系统,所以访问同一个文件,或同一个打印终端,是没有问题的,part1:共享同一打印终端,发现会有多行内容打印到一行的现象(多个进程共享并抢占同一个 ...

  5. cocos子节点转父节点坐标 原理浅析(局部坐标转世界坐标同理)

    在CCNode的类中,有一个得到 一个节点坐标系转换父亲坐标系的一个矩阵,节点内坐标乘以这个矩阵,就可以转换为在节点父节点中的坐标,方法名为: Mat4& Node::getNodeToPar ...

  6. css实战第三天小结

    1.谈一谈对层级的理解: 如果对两个并列的子元素都设置了相对于同一个父元素(如果没有设置父元素那么默认相对于浏览器而言)进行了定位(相对定位),则这两个都具有相同的层级(默认为0),他们的trbl也默 ...

  7. tp5 post接到的json被转义怎么解决???

    $data =input('post.');//用户唯一标识$goods = $data['goods']; $shopcuxiao=$data['shopcuxiao']; $goods=htmls ...

  8. 解决KVM中宿主机通过console无法连接客户机

    转自https://www.linuxidc.com/Linux/2014-10/107891.htm 一.问题描述: KVM中宿主机通过console无法连接客户机,卡在这里不动了. # virsh ...

  9. Postgresql ERROR: permission denied for relation app_info

    启用终端,: 进入mydb数据库:\c mydb 然后给当前数据库的角色赋予权限:GRANT ALL PRIVILEGES ON TABLE 表名  TO 角色名;

  10. jsfiddle修改个人头像

    找了半天终于知道修改jsfiddle头像的方法了~ JsFiddle将Gravatar - 全球认可的头像用于个人资料图片.必须在这里改变你的头像,它也会在jsFiddle中自动更新. 注意,两者的注 ...