Angular2: subscribe to BehaviorSubject not working
<p>I have an <code>Alert.Service.ts</code> which saves alerts fetched from another service in an array. In another <code>header.component.ts</code>, I want to get the real-time size of that array.</p>

<p>So, in <code>Alert.Service.ts</code> I have</p>

<pre><code>@Injectable()
export class AlertService {

public static alerts: any = [];

// Observable alertItem source
private alertItemSource = new BehaviorSubject&lt;number&gt;(0);
// Observable alertItem stream
public alertItem$ = this.alertItemSource.asObservable();

constructor(private monitorService: MonitorService) {
    if (MonitorService.alertAgg != undefined) {
        AlertService.alerts = MonitorService.alertAgg['alert_list'];
        AlertService.alerts.push({"id":111111,"severity":200}); //add a sample alert

        this.updateAlertListSize(AlertService.alerts.length);

        MonitorService.alertSource.subscribe((result) =&gt; {
            this.updateAlertList(result);
        });
    }
}

private updateAlertList(result) {
    AlertService.alerts = result['alert_list'];
    this.updateAlertListSize(AlertService.alerts.length);
}


// service command
updateAlertListSize(number) {
  this.alertItemSource.next(number);
}
</code></pre>

<p>And, in <code>header.component.ts</code>, I have</p>

<pre><code>@Component({
selector: 'my-header',
providers: [ AlertService  ],
templateUrl: 'app/layout/header.component.html',
styles: [ require('./header.component.scss')],
})

export class HeaderComponent implements OnInit, OnDestroy {
private subscription:Subscription;
private alertListSize: number;

constructor(private alertSerivce: AlertService) {

}

ngOnInit() {
    this.subscription = this.alertSerivce.alertItem$.subscribe(
        alertListSize =&gt; {this.alertListSize = alertListSize;});
}

ngOnDestroy() {
    // prevent memory leak when component is destroyed
    this.subscription.unsubscribe();
}
</code></pre>

<p>I expect the <code>alertListSize</code> gets updated as long as the <code>alerts</code> array in <code>Alert.Service.ts</code> changed. However, it's always <code>0</code> which is the initial value when the <code>BehaviorSubject</code> is created. It seems that the subscribe part doesn't work.</p>