angular_共享订阅结果_rx.js中share()的作用

2023-12-31 18:30:23

learn

import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
import { share } from 'rxjs';
import { SharedDataService } from '../shared-data.service';

@Component({
  selector: 'app-producer',
  templateUrl: './producer.component.html',
  styleUrls: ['./producer.component.less']
})
export class ProducerComponent {
  
  p=this.http.get("http://www.baidu.com").pipe(share())

  p1=this.p
  p2=this.p


  constructor(
    private readonly service: SharedDataService,
    private http:HttpClient,
    ) { }


  increaseCount() {
    this.service.setCount(1);
  }

  decreaseCount() {
    this.service.setCount(-1);
  }

  test(){
    this.p1.subscribe(console.log)
    this.p2.subscribe(console.log)
  }


}

p=this.http.get(“http://www.baidu.com”).pipe(share()) ,share()起到什么作用

在这段代码中,share()的作用是将可观察对象(Observable)转换为可共享的可观察对象,以便可以在多个订阅者之间共享它的结果。

具体来说,当一个可观察对象被订阅时,它会重新发起 HTTP 请求并返回一个新的响应。如果有多个订阅者,每个订阅者都会发起一个新的 HTTP 请求,这可能会导致网络资源的浪费和性能问题。

通过使用share(),第一个订阅者会发起 HTTP 请求并缓存响应,而后续的订阅者会直接使用缓存的响应,而不会重新发起 HTTP 请求。这样就可以避免发送多余的 HTTP 请求,提高性能并节省网络资源。

文章来源:https://blog.csdn.net/YuuuPeeiiiii/article/details/135317957
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。