如何关闭在Angular2中创建的HTTP连接的连接?

时间:2016-06-20 12:15:06

标签: node.js typescript angular event-stream

我正在开发一个示例cordova / ionic app。我正在使用angular2 /打字稿。我发出了一个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
}

1 个答案:

答案 0 :(得分:2)

.subscribe()会返回Subscription,允许您取消订阅:

this.subscription = this.response.subscribe(
    data => {
      doSomething(data);
    },
    err => console.error(err));
}

...

this.subscription.unsubscribe();