Angular 2 数组推送未从服务更新视图

Angular 2 array push not updating the view from a service

我有这样的服务:

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);
  }
}

我从这样的组件中调用它:

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'
            });
        }
    }
 }
}

当我向服务添加项目时,警报会如您所料触发,attachments.push。

但是,在我单击 DOM 上的任意位置之前,视图不会更新,然后任何后续添加的附件都会立即显示。

我在这里错过了什么?

你可以运行一个this.zone.run(() => {});触发页面重绘。

区域定义如下

public 区域:NgZone

您不改变变量本身,而是改变变量的内容。它仍然在记忆中的同一个地方。此时更改检测有时会失败。