溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

在TypeScript中如何使用RxJS

發(fā)布時(shí)間:2020-08-04 10:17:45 來源:億速云 閱讀:186 作者:小豬 欄目:web開發(fā)

這篇文章主要講解了在TypeScript中如何使用RxJS,內(nèi)容清晰明了,對此有興趣的小伙伴可以學(xué)習(xí)一下,相信大家閱讀完之后會有幫助。

1. 安裝

# 安裝 typescript, rxjs 包
npm install -D typescript @types/node
npm install rxjs

2. 使用

2.1 使用 from 來從數(shù)組生成源

RxJS 有許多創(chuàng)建源的方法,如 from, fromEvent..., 這里使用 from做個(gè)例子

import {from} from 'rxjs'

// 從數(shù)組生成可訂閱對象
// obser 的對象類型為 Observable
let obser = from([1,2,3,4,5])
// 消費(fèi)對象
// next 當(dāng)管道中有值流動,就會出發(fā)next
// 當(dāng)發(fā)生錯誤是會觸發(fā) error
// 當(dāng)循環(huán)完數(shù)組時(shí),會調(diào)用complete
obse.subscribe({
  next(item) {
    console.log(item)
  },
  error(err) {
    console.log(err)
  },
  complete() {
    console.log("Done")
  }
}

2.2 自定義生成源

import {Observable, from} from 'rxjs'

// 新建一個(gè)可訂閱對象
let obser = new Observable<string>(productor => {
  // 自定義數(shù)據(jù)流
  productor.next("hello")
  productor.next("world")
  setTimeout(()=>{
    productor.next("After 1 Sec")
    productor.complete()
  }, 1000)
})

// 消費(fèi)
obse.subscribe({
  next(item) {
    console.log(item)
  },
  error(err) {
    console.log(err)
  },
  complete() {
    console.log("Done")
  }
}

3. 實(shí)際例子,使用 Redis

3.1 安裝 Redis

npm install redis @types/redis

3.2 使用

import {RedisClient} from "redis"
import {Observable} from "rxjs"
// 連接redis, redisclient 的構(gòu)造類型是”ClientOpt接口“,只要是符合其字段定義的對象就可以
let reids = new RedisClient({
  host:"localhost",
  port:6379
})
// redis的操作都是異步操作,通過回調(diào)使用,很容易陷入毀掉地獄
redis.set("name", "tom", (err, res)=>{
  // 需要在set成功后同步的操作
  if(!err) {
    redis.get("name", (err,res)=> {
      console.log(res)
    })
  }
})

// 可以使用 Promise 封裝上面的方法,但我們這里使用 rxjs的事件流
let redisObser = new Observable(productor => {
// 這個(gè)列子沒啥實(shí)際用途,只做演示
  redis.set("name", "jack", (err, res) => {
    productor.next(res)
    productor.complete()
  })
})
// 消費(fèi)代碼
obse.subscribe({
  next(key) {
    // 讀取或其他需保證在 set 后的操作
    redis.get(key, (err, res) => {
      console.log(res)
    })
  },
  error(err) {
    console.log(err)
  },
  complete() {
    console.log("Query Finish")
  }
}

看完上述內(nèi)容,是不是對在TypeScript中如何使用RxJS有進(jìn)一步的了解,如果還想學(xué)習(xí)更多內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI