如何消费"永无止境的"有角度2的数据流?我正在写一个小聊天应用程序,其中一个服务器用go编写,一个客户端用angular2编写。对于推送服务,我实现了一个端点,可以保持连接。授权用户可以使用GET请求连接到server.com:123/broker
上的消息代理。每当用户的新消息到达时,它就以json-object的形式发送给代理。然而,当使用normale语法时,我不会得到任何结果(因为代码等待连接被关闭,如我所想):
return this._http.request(req).map( (res: Response) => {
return res.json();
}).subscrube( results => {
console.log("results arrived", results);
});
消费流有很多优点(例如带有休息api的视频流,真棒)。有没有办法做到这一点?
/ edit:这里有更多信息: 我检查了http事务,看起来没问题:
GET /broker HTTP/1.1
User-Agent: curl/7.35.0
Host: mydomain.com:12345
Accept: */*
Authorization: Bearer [JWT]
带有响应标头的服务器ansers:
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Date: Mon, 01 Feb 2016 11:16:45 GMT
Transfer-Encoding: chunked
[然后客户端正在侦听此连接,直到服务器将某些内容推送到流
中ba
{"target":"56addcef7bec6d5785ee6945","payload": ...}
到目前为止似乎是正确的。我可以看到以十六进制(ba),CRLF,有效负载(json)和最终CRLF的块的大小。所以,在谈论HTTP标准时,一切似乎都没问题。但是,我的Angular2不会获取这些块。
答案 0 :(得分:5)
正如其中一条评论中已经提到的,目前Angular2本身无法实现,已经记录了一项功能请求(2015年6月起):查看here
要在功能实现之前完成工作,我现在Oboe.js作为外部API。
在package.json
中添加依赖关系:
"dependencies": {
"oboe": "*",
...
},
不要忘记运行npm install
或下载软件包等。
在index.html
<script src="node_modules/oboe/dist/oboe-browser.min.js"></script>
使用oboe来使用http-stream
import {Injectable, OnInit} from 'angular2/core';
// Declare oboe as a Variable
declare var oboe: any;
@Injectable()
export class BrokerService {
private oboeService: any;
constructor() {
this.listen();
}
listen(): void {
console.log("registering message broker")
var config = {
'url': 'https://you-streaming-api.com:123/broker',
'method': "GET",
'headers': {'Authorization': 'Bearer ' + this._jwToken },
'body': '',
'cached': false,
'withCredentials': true
}
this.oboeService = oboe(config);
// The '!' will only consume complete json objects
this.oboeService.node ('!', function (thing) {
console.log("new broker message", thing);
});
}
}
答案 1 :(得分:1)
我认为您需要实现一个自定义backend,它会单独转发它收到的每个事件,而不是仅转发整个结果。
此备用后端可以注册为DI,可以在任何地方使用,而不是原始的,或者仅在明确请求时使用。后者还需要一个替代的Http
实现来区分默认和流式实现,因为这种类型是实际注入组件或服务的类型。后端只是Http
请求的传递依赖。
答案 2 :(得分:0)
就我而言,const oboe = require('oboe');
代替了 declare var oboe: any;
环境:Ionic 5 和 Angular 9
更新代码:
const oboe = require('oboe'); <<<---- Updated code
@Injectable()
export class BrokerService {
private oboeService: any;
constructor() {
this.listen();
}
listen(): void {
console.log("registering message broker")
var config = {
'url': 'https://you-streaming-api.com:123/broker',
'method': "GET",
'headers': {'Authorization': 'Bearer ' + this._jwToken },
'body': '',
'cached': false,
'withCredentials': true
}
this.oboeService = oboe(config);
// The '!' will only consume complete json objects
this.oboeService.node ('!', function (thing) {
console.log("new broker message", thing);
});
}
}