我有这段代码:
this.http.get(url)
.subscribe(
data => {
},
error=>{
}
)
我该如何关闭一个HTTP连接?
//Create connection
URL url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
...
connection.disconnect();
如果你使用Angular来进行HTTP请求,就不需要这样做。Angular使用XHR浏览器API来进行HTTP请求。这个API不需要显式地打开或关闭连接,一旦请求被发送并且收到响应或超时,它会自动执行。
另外,你不需要显式地取消订阅observable,因为this.http.get
返回的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);
};
< p > 在 XHRConnection
内创建的可观察对象是您在执行 http.get()
时收到的可观察对象。