I have a service like so:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import {AttachmentModel} from "../view-attachments/attachment.model";
@Injectable()
export class AttachmentService {
// Observable array sources
private attachmentSource = new Subject<AttachmentModel>();
// Observable array streams
attachmentAdded$ = this.attachmentSource.asObservable();
// Service commands
addAttachment(attachment: AttachmentModel) {
this.attachmentSource.next(attachment);
}
}
and I call it from a component like so:
import {Component, OnInit, Input, ChangeDetectorRef, EventEmitter, Output} from '@angular/core';
import {AttachmentModel} from "./attachment.model";
import {AttachmentService} from "../services/AttachmentService";
@Component({
selector: 'view-attachments',
templateUrl: './view.component.html',
styleUrls: ['./view.component.css']
})
export class ViewComponent implements OnInit {
public attachments;
public attachment: AttachmentModel;
constructor(private attachmentService: AttachmentService) {
this.attachments = [];
}
ngOnInit() {
this.attachmentService.attachmentAdded$.subscribe(
attachments => {
alert();
this.attachments.push(attachments);
this.attachments = this.attachments.slice();
}
);
}
handleGoogleFiles = (files) => {
if (typeof(files) !== 'undefined') {
for (let file of files) {
this.attachmentService.addAttachment({
deleted: false,
resource_drive_file: file,
resource_type: 'liveDrive',
resource_drive_share_type: 'copy'
});
}
}
}
}
When I add an item to the service the alert fires as you would expect and so does the attachments.push.
However, the view is not updated until I click anywhere on the DOM and then any subsequent attachment additions show straight away.
What am I missing here?
handleGoogleFiles? Are you sure that it is executed within angular zone?