如何关闭 HTTP 连接?

Mar*_*ars 3 http angular

我有这个代码:

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

  },
  error=>{

  }
)
Run Code Online (Sandbox Code Playgroud)

如何关闭 HTTP 连接?

Max*_*kyi 5

如果您谈论的是类似于在 Java 中所做的事情的类比:

//Create connection
URL url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
...
connection.disconnect();
Run Code Online (Sandbox Code Playgroud)

那么你不需要这样做。Angular 使用XHR 浏览器 API来发出 HTTP 请求。此 API 不需要显式打开或关闭连接,它会在发送请求并获得响应或超时后自动执行。

此外,您不需要显式取消订阅 observable,因为 observable 由this.http.get完成本身返回。以下是相关来源:

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);
            };
Run Code Online (Sandbox Code Playgroud)

内部创建XHRConnection的 observable 是您在执行时收到的 observable http.get()