iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 22
0
Modern Web

Vue菜鳥的自我學習days系列 第 22

22. Rxjs 處理非同步

意非同
步的問題,雖然可以使用 ajax callback、promise 等方式處裡,但一旦處理程序過多,容易造成程式維護上的不便
性,接下來我們使用 json-server 模擬遠端環境,透過 RESTful API 方式取得資料,並且以 Rxjs 來處理

json-server
首先安裝 json-server,在終端機輸入 npm install -g json-server 來全域安裝

npm install -g json-server

之後在欲儲存資料的位置上新增 db.json,這裡可以根目錄下,db.json 內容如下:

{
"products": [
{
"id": 1,
"name": "Car",
"imgUrl": "https://images.pexels.com/photos/1200458/pexels-photo-1200458.jpeg?
auto=compress&cs=tinysrgb&h=350",
"desc": "A luxury car you won't miss it.",
"price": 199.99
},
{
"id": 2,
"name": "Bike",
"imgUrl": "https://images.pexels.com/photos/1239460/pexels-photo-1239460.jpeg?
auto=compress&cs=tinysrgb&h=350",
"desc": "A durable bike you've never ride.",
"price": 25.00
}
]
}

之後開啟 json-server 監聽,在終端機輸入下面指令:

json-server --watch db.json

VueRx with Rxjs
伺服器已經成功建置,接著安裝 VueRx 及 Rxjs 套件,在終端機輸入:

npm install vue-rx rxjs --save

安裝完成後在 main.js 使用 VueRx 模組

import Vue from 'vue';
import VueRx from 'vue-rx';
...
Vue.use(VueRx);
...

由於透過 rxjs 使用 Observable 的方式來進行資料處理,接著我們更改 product-service 的資料取得邏輯,原本的get 方法改為利用 rxjs/ajax 回傳 Observable 物件,另外使用 catchError operator 來處理錯誤例外

import { ajax } from 'rxjs/ajax';
import { catchError } from 'rxjs/operators';
// data source url
const sourceUrl = 'http://localhost:3000/products';
export default {
get(id) {
const url = id ? `${sourceUrl}/${id}` : sourceUrl;
return ajax.get(url).pipe(
catchError((err) => {
throw err;
}),
);
},
};

另外因為資料 domain (localhost:3000) 與前端 domain (localhost:8081) 不同,需要處理 CORS 問題,所以在
headers 加上 Access-Control-Allow-Origin 設定,並在 ajax.get 傳入 headers 參數

import { ajax } from 'rxjs/ajax';
import { catchError } from 'rxjs/operators';
const sourceUrl = 'http://localhost:3000/products';
const headers = {
'Access-Control-Allow-Origin': 'http://localhost:3000',
};
export default {
get(id) {
const url = id ? `${sourceUrl}/${id}` : sourceUrl;
return ajax.get(url, headers).pipe(
catchError((err) => {
throw err;
}),
);
},
};

上一篇
21.Unit test2
下一篇
23.Rxjs 處理非同步2
系列文
Vue菜鳥的自我學習days39
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言