2016-06-20 4 views
0

샘플 cordova/ionic app을 개발 중입니다. angular2/typescript를 사용하고 있습니다. node.js 서버에서 이벤트 스트림을 처리하도록하는 GET 요청을 발행했습니다. 이 연결을 닫으 려합니다. 어떻게해야합니까?Angular2에서 생성 된 HTTP 연결을 어떻게 닫습니까?

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 
} 

답변

2

.subscribe() 당신이 취소 할 수있는 Subscription를 반환

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

... 

this.subscription.unsubscribe(); 
+0

완벽한합니다. 감사. :) – georgekuruvillak

관련 문제