Angular2: Too many calls on Observable

296 views Asked by At

So currently I created a service in order to path data from one component to another. Let's say I have a select component and a component factory. In order to pass a selected value from a select component to factory I designed this service.

Here is how the service looks like:

import { Injectable } from '@angular/core';
import {Subject} from "rxjs/Subject";

@Injectable()
export class ObservableService {
    private dataSource = new Subject();
    data = [];
    data$ = this.dataSource.asObservable();

    updateFilter(value) {
        this.data.push(value);
        console.log('Changes transfer');
        this.dataSource.next(this.data)
    }
}

So, as I said I have to path data from my html select input that belongs to select component to factory, and here is the select component html

<select (change)="onChange($event)">
    <option value="">Options</option>
    <option *ngFor="let option of options" [value]="option.value">{{ option.name }}</option>
</select>

And here is the way I sending selected value from select component to observable service:

private onChange(option) {
    console.log('Changes sent');
    this._observable.updateFilter(option);

}

Here is how I'm catching data in factory component

ngOnInit() {
    this._observable.data$.subscribe(
        data => console.log('Changes detected');
    )
}

You may notice console commands that I put on each stage of data transfer. And in fact I got this:

Changes sent
Changes transfer
(13) Changes detected

So in fact the observable subscriber detected 13 changes! Please, help me to understand where this strange behavior goes from?

0

There are 0 answers