如何关闭在 Angular2 中创建的 HTTP 连接?
How do I close the connection an HTTP connection created in Angular2?
我正在开发示例 cordova/ionic 应用程序。我正在使用 angular2/typescript。我发出了一个 GET 请求,让我可以处理来自 node.js 服务器的事件流。我想关闭这个连接。我该怎么做?
ionViewWillEnter(){
// Register for SSE Events
var sseUrl = this.hostUrl + '/api/v1/br/notifications';
this.response = this.http.get(sseUrl).map(res => res.json());
this.response.subscribe(
data => {
doSomething(data);
},
err => console.error(err));
}
ionViewWillLeave(){
// What should I do here??
}
服务端代码如下:
//API: POST /notifications
function getNotifications(req, res){
req.socket.setTimeout(0);
addListeners(res, notify);
//send headers for event-stream connection
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
res.write('\n');
req.on("close", function() {
console.log("Close called...");
removeListener(res);
});
}
function notify(data, notifier){
console.log(util.format('Sending: Data: %s', data));
notifier.res.write('data: ' + data + '\n\n'); // Note the extra newline
}
.subscribe()
returns 允许您退订的 Subscription
:
this.subscription = this.response.subscribe(
data => {
doSomething(data);
},
err => console.error(err));
}
...
this.subscription.unsubscribe();
我正在开发示例 cordova/ionic 应用程序。我正在使用 angular2/typescript。我发出了一个 GET 请求,让我可以处理来自 node.js 服务器的事件流。我想关闭这个连接。我该怎么做?
ionViewWillEnter(){
// Register for SSE Events
var sseUrl = this.hostUrl + '/api/v1/br/notifications';
this.response = this.http.get(sseUrl).map(res => res.json());
this.response.subscribe(
data => {
doSomething(data);
},
err => console.error(err));
}
ionViewWillLeave(){
// What should I do here??
}
服务端代码如下:
//API: POST /notifications
function getNotifications(req, res){
req.socket.setTimeout(0);
addListeners(res, notify);
//send headers for event-stream connection
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
res.write('\n');
req.on("close", function() {
console.log("Close called...");
removeListener(res);
});
}
function notify(data, notifier){
console.log(util.format('Sending: Data: %s', data));
notifier.res.write('data: ' + data + '\n\n'); // Note the extra newline
}
.subscribe()
returns 允许您退订的 Subscription
:
this.subscription = this.response.subscribe(
data => {
doSomething(data);
},
err => console.error(err));
}
...
this.subscription.unsubscribe();