Angular 中RxJS练习

元素拖拽

HTML

<style>
#box {
width: 200px;
height: 200px;
background: skyblue;
position: absolute;
left: 0;
top: 0;
}
</style>
<div id="box"></div>

JS

box.onmousedown = function (event) {
let distanceX = event.clientX - event.target.offsetLeft
let distanceY = event.clientY - event.target.offsetTop
document.onmousemove = function (event) {
let positionX = event.clientX - distanceX
let positionY = event.clientY - distanceY
box.style.left = positionX + "px"
box.style.top = positionY + "px"
}
box.onmouseup = function () {
document.onmousemove = null
}
}

RxJS

import { fromEvent } from "rxjs"
import { map, switchMap, takeUntil } from "rxjs/operators"
const box = document.getElementById("box")
fromEvent(box, "mousedown")
.pipe(
map(event => ({
distanceX: event.clientX - event.target.offsetLeft,
distanceY: event.clientY - event.target.offsetTop
})),
switchMap(({ distanceX, distanceY }) =>
fromEvent(document, "mousemove").pipe(
map(event => ({
positionX: event.clientX - distanceX,
positionY: event.clientY - distanceY
})),
takeUntil(fromEvent(document, "mouseup"))
)
)
)
.subscribe(({ positionX, positionY }) => {
box.style.left = positionX + "px"
box.style.top = positionY + "px"
})

搜索

<input id="search" type="text" placeholder="请输入搜索内容..." />
import { fromEvent, from, throwError } from "rxjs"
import { debounceTime, distinctUntilChanged, map, switchMap, catchError } from
"rxjs/operators"
import axios from "axios"
const search = document.getElementById("search")
fromEvent(search, "keyup")
.pipe(
debounceTime(700),
map(event => event.target.value),
distinctUntilChanged(),
switchMap(keyword =>
from(
axios.get(`https://j1sonplaceholder.typicode.com/posts?q=${keyword}`)
).pipe(
map(response => response.data),
catchError(error => throwError(`发生了错误: ${error.message}`))
)
)
)
.subscribe({
next: value => {
console.log(value)
},
error: error => {
console.log(error)
}
})

串联请求

<button id="btn">获取用户信息</button>
import axios from "axios"
import { from, fromEvent } from "rxjs"
import { pluck, concatMap } from "rxjs/operators"
const button = document.getElementById("btn")
fromEvent(button, "click")
.pipe(
concatMap(event =>
from(axios.get("http://localhost:3005/token")).pipe(
pluck("data", "token")
)
),
concatMap(token =>
from(axios.get("http://localhost:3005/userInfo")).pipe(pluck("data"))
)
)
.subscribe(console.log)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值