# RxJS **Repository Path**: duans/rxjs ## Basic Information - **Project Name**: RxJS - **Description**: RxJS可观察对象初探 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2019-12-15 - **Last Updated**: 2022-06-28 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # RxJS入门指引 ## 什么是RxJS > x 是 Reactive Extension(也叫 ReactiveX)的简称,指的是实践响应式编程的一套工具,Rx 官网首页的介绍是一套通过可监听流来做异步编程的 API(An API for asynchronous programming with observable streams)。 Rx 最早是由微软开发的 LinQ 扩展出来的开源项目,之后由开源社区维护,有多种语言的实现,如 Java 的 RxJava,Python 的 RxPY 等,而 RxJS 就是 Rx 的 JavaScript 语言实现。 > RxJS实现了一种可观察对象, 用来优化异步代码和通过回调函数实现的异步代码 ## 安装 - npm安装: `npm i rxjs -S` ## 使用 ### 创建一个可观察对象 ```js // import {Observable} from 'rxjs'; // observable是一个可观察的对象 const observable$=new Observable((observer)=>{ // 通过next()发布数据 observer.next({name:'zs',age:30}); // 通过error()抛出异常 observer.error(new Error('出错了')); // complete()表示数据发布完成 observer.complete() }) ``` - 订阅对象 ```js observable$.subscribe({ // 接收observer.next()发布的数据 next(data){ console.log(data); }, // 捕获observer.error()抛出的异常 error(err){ console.log(err); }, // 数据结束完毕(如果抛出异常, 则complete()不会被触发) complete(){ console.log('数据结束完毕'); } }) ``` ### 通过ajax发送网络请求 - 发送get请求 ```js // 导入ajax对象 import {ajax} from 'rxjs/ajax'; // 02-通过rxjs提供的ajax实现数据请求 const url='http://106.13.182.88:8081/get.php'; const response$=ajax(url); response$.subscribe({ next({response}){ console.log(response); } }); ``` - getJSON直接发送get请求 ```js const url='http://106.13.182.88:8081/get.php'; const response$=ajax.getJSON(url); response$.subscribe({ next(res){ console.log(res); } }); ``` - 发送post请求 ```js const url = 'http://106.13.182.88:8081/post.php'; const post$ = ajax({ url, method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'rxjs-custom-header': 'Rxjs' }, body: { rxjs: 'Hello World!' } }) post$.subscribe(({ response }) => { console.log(response); }); ``` ### fromEvent ```js // 03-fromEvent()将事件转换成Observable了观察对象 const btn=document.querySelector('#btn'); const btn$=fromEvent(btn,'click'); btn$.subscribe({ next(data){ console.log(data); // 设置成禁用状态, 实现只能点击一次 btn.setAttribute('disabled', '') } }); ``` ### from ```js // 04-from()将其对象转化成Observable可观察对象 // 可以传入Observable, Array, Promise, Iterable const obj$=from([100,200]); obj$.subscribe({ next(data){ console.log(data); } }); ``` ### range ```js // 05-range()创建一个可迭代的Observable可观察对象 const range$=range(1,4); range$.subscribe((data)=>{ console.log(data); }); ``` ### of ```js // 05-of()创建一个可迭代的Observable可观察对象 const of$=of(1,20,1024); of$.subscribe((data)=>{ console.log(data); }); ``` ### webSocket - 监听服务端的消息 ```js import { webSocket } from "rxjs/webSocket"; const subject = webSocket("ws://localhost:8081"); subject.subscribe( msg => console.log('message received: ' + msg), // Called whenever there is a message from the server. err => console.log(err), // Called if at any point WebSocket API signals some kind of error. () => console.log('complete') // Called when connection is closed (for whatever reason). ); ``` - 向服务端发送消息 ```js import { webSocket } from "rxjs/webSocket"; const subject = webSocket('ws://localhost:8081'); subject.subscribe(); // Note that at least one consumer has to subscribe to the created subject - otherwise "nexted" values will be just buffered and not sent, // since no connection was established! subject.next({message: 'some message'}); // This will send a message to the server once a connection is made. Remember value is serialized with JSON.stringify by default! subject.complete(); // Closes the connection. subject.error({code: 4000, reason: 'I think our app just broke!'}); // Also closes the connection, but let's the server know that this closing is caused by some error. ``` ## 参考文档 - [英文文档](https://rxjs-dev.firebaseapp.com/guide/overview) - [博客园](https://www.cnblogs.com/ang-/p/9514430.html) - [mooc](https://www.imooc.com/article/70323)