代码之家  ›  专栏  ›  技术社区  ›  Raphaël VO

减少角2组件的服务需求

  •  0
  • Raphaël VO  · 技术社区  · 7 年前

    上下文:我有一个服务从服务器调用数据,以及三个组件A、B和C,它们调用这个服务来获取相同的数据。在Angular2+中,有没有一种方法可以告诉组件B和C,服务调用已经由A调用,只需等待数据处理?

    我想我需要为这个案例使用cache或observable,但我无法想象如何做到这一点?

    编辑

    我的服务:

    currentAccount<Account>;
    
    getCurrentAccount(): Observable<Account> {
        if (this.currentAccount && this.currentAccount.id) {
          return Observable.of(this.currentAccount);
        } else {
          return this.http.get<Account>(this.url).pipe(
            tap(account => {
              this.currentAccount = account;
        }));
    }
    

    组件A、B和C现在:

    this.service.getCurrentAccount().subscribe(account => {
        // Do something
    });
    

    假设我把上面的三个组件都放在同一个容器中。我应该如何调用BehaviorSubject?这3个组件也可以在其他页面中使用,它将保持独立,需要调用数据本身。

    1 回复  |  直到 7 年前
        1
  •  1
  •   SiddAjmera    7 年前

    当然。由于这是共享服务,因此可以公开 BehaviorSubject 来自此服务 asObservable . 然后 subscribe 从这三个部分。

    一旦将数据提取到服务中,就可以调用 next 方法 行为主体 在这三个部分中, 订阅 为了这个 行为主体 .

    这就是它将如何转换为代码:

    共享服务:

    private sharedData: BehaviorSubject<any> = new BehaviorSubject<any>(null);
    sharedData$ = this.sharedData.asObservable();
    
    getData() {
      this.http.get('YOUR_API_URL').subscribe(data => this.sharedData.next(data));
    }
    

    A部分:

    this.sharedService.sharedData$.subscribe(data => this.data = data);
    this.sharedService.getData();
    

    部件B和部件C:

    this.sharedService.sharedData$.subscribe(data => this.data = data);
    

    更新:

    考虑到您不想多次调用,您可以直接将sharedata作为对象公开。对象在JavaScript中通过引用传递。所以注射 SharedService 在所有三个组件中,然后引用 sharedData 这三个部分都相同。如果 共享数据 对一个组件(比如A)所做的更改,也会反映到组件B和C,因为它们共享对内存中同一对象的引用。

    然后,SharedService的实现将更改为以下内容:

    sharedData;
    
    getData() {
      return this.http.get('YOUR_API_URL').pipe(
        tap(data => this.sharedData = data)
      );
    }
    

    现在就叫这个 getData 在检查是否 共享数据 undefined 或者没有。

    所以在所有的A、B和C组分中,

    if(this.sharedService.sharedData) {
      // Use sharedData
      this.data = this.sharedService.sharedData;
    }
    else {
      this.sharedService.getData().subscribe(data => this.data = data);
    }