如果我们不订阅 return 在 angular 中观察到的 HttpClient 请求会发生什么

what happens if we does not subscribe to HttpClient request which return observables in angular

我是 Angular 和 typescript 的新手,正在尝试了解 HttpClientobservablessubscribe

当我在组件的函数中执行此操作时

console.log(this.http.get('assets/user.json'));

我正在接收一个对象,但在调试器 network 中看不到任何发送到 https://localhost:4200/assets/user.json 的请求,而如果我将代码更改为

this.http.get('assets/userDetail.json').subscribe(data => this.user = { name:  data['name']});

我可以看到网络请求达到了要求 URL。为什么会这样?我的理解是 this.http.get('assets/userDetail.json') 即使我们不订阅响应数据流也会命中 url。

要了解这个问题,最好知道有 hotcold observables - 需要订阅 cold 否则它们是未被解雇,无论是否订阅了热点都会被解雇。

Angular 的 HttpClient returns 是一个冷的 Observable,因此它在订阅之前不会被触发。要确定可观察对象是热的还是冷的,您需要检查相应的文档,例如 HttpClient.post:

Constructs an Observable which, when subscribed, will cause the configured POST request to be executed on the server.

Angular 的热可观察对象的一个​​示例是例如ActivatedRoute.params - how to use - 你看没有订阅。

事实是一个可观察的 hot/cold 比仅仅有或没有订阅有更多的后果:

  • 订阅时,您还应该取消订阅 to avoid memory leaks plus there is Angular's async pipe, which manages subscription for you; there is an article on the matter: Don't forget to unsubscribe(Angular具体)

  • Ben Lesh 有一篇关于这个主题的完美文章,从一般的角度来看:Hot vs Cold Observables(不特定于 Angular)。

前面的回答已经解释了为什么没有任何订阅者它就无法工作。因为它是一个冷观察者,所以只有当它至少找到一个订阅者时才会执行。

所以备选方案基本上是:

 this.http.get('assets/user.json').subscribe();

值得一提的是,假设这样的代码和冷可观察性:

(伪代码)

分量:

ngOnInit(): void {
    console.log('Before, in ngInit')
    usersService.usersGet();
    console.log('After, in ngInit')
}

服务:

public usersGet(){
   console.log("I'm in service");
   let data = this.http.get('assets/user.json')
   console.log("I'm already here")
   return data;
}

您将在浏览器的开发工具中看到这样的输出:

但是您的后端端点不会收到任何请求。

当您将代码更改为:

时,您的后端将得到请求思考
ngOnInit(): void {
    console.log('Before, in ngInit')
    usersService.usersGet().subscribe( x=> {
        console.log("I'm inside of subscribe")
        console.log(x)
    });
    console.log('After, in ngInit')
}

输出将是:

概述:在此代码片段中,我使用对整个应用程序可见的可注入创建了一个 webapi 服务。我订阅了 http.get 从调用函数返回的 observable。 IView 的结果类似于promise 绑定到数据列表。现在可以在其他组件构造函数中注入 WebApiService。

myComponent.component.ts

 public data: IDataView[];

调用可观察对象。 this.app.getMyViews('123').subscribe(result=>{this.data=result;});

WebApi.service.ts

@可注射({ 提供于:'root' })

export class WebApiService
{
   constructor(private http: HttpClient,private env:             EnvironmentUrlService) {     }

getMyViews(id)
    {
        var path = this.env.urlAddress + '/my_class/GetData/'+id;
        return this.http.get<IDataView[]>(path);

  }

}