2017-08-07 163 views
2

我有这样的代码:如何关闭HTTP连接?

this.http.get(url) 
.subscribe(
    data => { 

    }, 
    error=>{ 

    } 
) 

如何我可以关闭HTTP连接?

//Create connection 
URL url = new URL(targetURL); 
connection = (HttpURLConnection) url.openConnection(); 
... 
connection.disconnect(); 

那么你并不需要做的是:

+0

你是指什么意思关闭? –

+0

@Keerthi,连接是开放的,但隐含。看到我的回答 –

+0

我的不好。感谢您指出。删除错误的评论。 – Keerthi

回答

4

如果像它在Java中的完成你在谈论的模拟的东西。 Angular使用XHR browser API来发出HTTP请求。此API不需要显式打开或关闭连接,一旦发送请求并获取响应或超时,它就会自动执行此操作。

另外,由于this.http.get返回的observable自身完成,因此您不需要明确地取消订阅observable。下面是相关来源:

export class XHRConnection implements Connection { 
    ... 
    response: Observable<Response>; 
    constructor(req: Request, browserXHR: BrowserXhr, baseResponseOptions?: ResponseOptions) { 
     this.request = req; 
     this.response = new Observable<Response>((responseObserver: Observer<Response>) => { 
      ... 
      // load event handler 
      const onLoad =() => { 
       ... 
       const response = new Response(responseOptions); 
       response.ok = isSuccess(status); 
       if (response.ok) { 
        responseObserver.next(response); 
        responseObserver.complete(); <-------------------- 
        return; 
       } 
       responseObserver.error(response); 
      }; 

XHRConnection创建的可观察到的是你收到观察到,当你做http.get()

+1

ty男人,谢谢你的信息;) – Mars