I am developing an sample cordova/ionic app. I am using angular2/typescript. I have issued a GET request that gives me handle over an event-stream from a node.js server. I would like to close this connection. How can I do that?
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??
}
Server side code is as shown below:
//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 a Subscription
that allows you to unsubscribe:
this.subscription = this.response.subscribe(
data => {
doSomething(data);
},
err => console.error(err));
}
...
this.subscription.unsubscribe();