简体   繁体   English

Angular2 +异步管道:从单个Observale获取多个值

[英]Angular2 + async pipe: Get multiple values from a single Observale

I have a single Service, which returns a single Observable. 我有一个Service,它返回一个Observable。 Now I'm looking for the correct / most efficient way to get multiple results from this Observable without writing too much code. 现在我正在寻找正确/最有效的方法来从这个Observable获得多个结果,而无需编写太多代码。

  • MyService returns an Observable<Array<Foo>> MyService返回一个Observable<Array<Foo>>

  • MyComponent calls myService.getFoos() and should output the first 5 elements from the array, and the total length of the array, and the number of elements not shown. MyComponent调用myService.getFoos()并应输出数组中的前5个元素,数组的总长度以及未显示的元素数。

Here's my current code: 这是我目前的代码:

@Injectable()
export class MyService {
  foos = new BehaviorSubject<Array<Foo>>([]);

  getFoos() {
    return this.foos.asObservable();
  }
}



@Component({
  template: `
    Total: {{ totalCount | async }}
    Omitted: {{ (totalCount | async) - (maxFiveItems | async).length }}
    <div *ngFor="let item of maxFiveItems | async">
      {{item.bar}}
    </div>
  `
})
export class MyComponent {
  totalCount: Observable<number>;
  maxFiveItems: Observable<Array<Foo>>;

  constructor(myService:MyService) {
    this.totalCount = myService.getFoos()
        .map(arr => arr.length);

    this.maxFiveItems = myService.getFoos()
        .map(arr => arr.slice(0, 5));
  }
}

The result looks fine, but I'm using the async pipe 4 times. 结果看起来很好,但我使用async管道4次。 Which (as far as I know) will result in 4 Subscriptions. 其中(据我所知)将导致4个订阅。 This shouldn't be necessary at all I guess (?) 根本不应该这是必要的(?)


Of course I could manually subscribe within the constructor of MyComponent and then live without async pipes. 当然,我可以在MyComponentconstructor中手动订阅,然后在没有async管道的情况下生存。 But then I have to take care of unsubscribing myself. 但是我必须要照顾自己取消订阅。

Is there any other way to handle this? 有没有其他方法来处理这个?

There's nothing wrong with what you're doing assuming that myService.getFoos() somewhere inside uses share() operator so all your async pipes share the same subscription to the source. 假设myService.getFoos()里面的某个地方使用了share()运算符,那么你正在做的事情没有错,所以你的所有async管道共享相同的源订阅。 If you're using BehaviorSubject as in this example then you're fine. 如果您在此示例中使用BehaviorSubject ,那么您没问题。

What you mentioned about subscribing yourself in the constructor is what came to my mind immediately. 你提到的关于在构造函数中订阅自己的内容是我立刻想到的。 I don't see manual unsubscription as a problem though. 我不认为手动取消订阅是一个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM