Angular2 - Subscribe when two event emmitters emit

I have the following code for my component:

ngOnInit() {
    this.route.params.forEach((params: Params) => {
        this.codvis = params['id'];
    });
    this.objects.selectedObject.subscribe(obj => this.selectedEventObjet(obj));
    this.sections.selectecSection.subscribe(section => this.selectedEventSection(section));
}

function selectedEventObjet(o) {
    this.selectedObj = o;
}

function selectedEventSection(s) {
    this.selectedSection = s;
}

So, now I want to call a service only when selectedObj and selectedSection are set, but it is not just simple as:

ngOnInit() {
    this.route.params.forEach((params: Params) => {
        this.codvis = params['id'];
    });
    this.objects.selectedObject.subscribe(obj => this.selectedEventObjet(obj));
    this.sections.selectecSection.subscribe(section => this.selectedEventSection(section));
    this.myService.getItems(this.selectedObj, this.selectedSection)
        .subscribe(
            items => this.items = items;
        );
}

But I can not obtain the items.

How can I make sure that selectedObj and selectedSection are set to get the items?

Upvotes: 1

Views: 499

Answers (1)

Meir
Meir

Reputation: 14385

Observable.combineLatest(this.objects.selectedObject, this.sections.selectecSection)
  .subscribe(([obj, section]) =>  this.myService.getItems(obj, section))

You don't even need your local handlers to keep the value, just get it straight of the sequences.

Upvotes: 1

Related Questions