我有这段代码:
this.http.get(url)
.subscribe(
data => {
},
error=>{
}
)
如何关闭HTTP连接?
答案 0 :(得分:4)
如果你在谈论类似于用Java完成的东西:
//Create connection
URL url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
...
connection.disconnect();
然后你不需要这样做。 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()
时收到的可观察对象。