mirror of
https://gitee.com/baidu/amis.git
synced 2024-12-02 11:58:10 +08:00
parent
7fdf80aadd
commit
3872b325bd
@ -394,12 +394,9 @@ Service 支持通过 WebSocket 获取数据,只需要设置 ws(由于无示
|
||||
}
|
||||
},
|
||||
"body": {
|
||||
{
|
||||
"label": "名称",
|
||||
"type": "input-text",
|
||||
"value": "name",
|
||||
"name": "amis"
|
||||
}
|
||||
"type": "static",
|
||||
"name": "name"
|
||||
}
|
||||
}
|
||||
```
|
||||
@ -430,6 +427,8 @@ WebSocket 客户端的默认实现是使用标准 WebSocket,如果后端使用
|
||||
|
||||
> 1.4.0 及以上版本修改了 ws 类型,将之前的字符串改成了对象的方式,会有两个参数 url 和 body
|
||||
|
||||
下面是目前 amis 中 WebSocket 支持的默认实现:
|
||||
|
||||
```javascript
|
||||
wsFetcher(ws, onMessage, onError) {
|
||||
if (ws) {
|
||||
@ -441,7 +440,17 @@ wsFetcher(ws, onMessage, onError) {
|
||||
};
|
||||
socket.onmessage = event => {
|
||||
if (event.data) {
|
||||
onMessage(JSON.parse(event.data));
|
||||
let data;
|
||||
try {
|
||||
data = JSON.parse(event.data);
|
||||
} catch (error) {}
|
||||
if (typeof data !== 'object') {
|
||||
let key = ws.responseKey || 'data';
|
||||
data = {
|
||||
[key]: event.data
|
||||
};
|
||||
}
|
||||
onMessage(data);
|
||||
}
|
||||
};
|
||||
socket.onerror = onError;
|
||||
@ -453,11 +462,48 @@ wsFetcher(ws, onMessage, onError) {
|
||||
close: () => {}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
通过 onMessage 来通知 amis 数据修改了,并返回 close 函数来关闭连接。
|
||||
|
||||
> 1.8.0 及以上版本
|
||||
|
||||
如果 WebSocket 返回的结果不是 JSON 而只是某个字符串,需要配置 `responseKey` 属性来将这个结果放在这个 key 上,比如下面的例子
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "service",
|
||||
"ws": {
|
||||
"url": "ws://localhost:8777?name=${name}",
|
||||
"data": {
|
||||
"name": "${name}"
|
||||
},
|
||||
"responseKey": "name"
|
||||
},
|
||||
"body": {
|
||||
"label": "名称",
|
||||
"type": "static",
|
||||
"name": "name"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
对应的后端就只需要返回字符串
|
||||
|
||||
```javascript
|
||||
const WebSocket = require('ws');
|
||||
|
||||
const ws = new WebSocket.Server({port: 8777});
|
||||
|
||||
ws.on('connection', function connection(ws) {
|
||||
setInterval(() => {
|
||||
const random = Math.floor(Math.random() * Math.floor(100));
|
||||
ws.send(random);
|
||||
}, 500);
|
||||
});
|
||||
```
|
||||
|
||||
## 调用外部函数获取数据
|
||||
|
||||
> 1.4.0 及以上版本
|
||||
|
@ -103,6 +103,7 @@ export interface RenderSchemaFilter {
|
||||
|
||||
export interface wsObject {
|
||||
url: string;
|
||||
responseKey?: string;
|
||||
body?: any;
|
||||
}
|
||||
|
||||
@ -296,7 +297,18 @@ const defaultOptions: RenderOptions = {
|
||||
};
|
||||
socket.onmessage = event => {
|
||||
if (event.data) {
|
||||
onMessage(JSON.parse(event.data));
|
||||
let data;
|
||||
try {
|
||||
data = JSON.parse(event.data);
|
||||
} catch (error) {}
|
||||
if (typeof data !== 'object') {
|
||||
let key = ws.responseKey || 'data';
|
||||
data = {
|
||||
[key]: event.data
|
||||
};
|
||||
}
|
||||
|
||||
onMessage(data);
|
||||
}
|
||||
};
|
||||
socket.onerror = onError;
|
||||
|
Loading…
Reference in New Issue
Block a user