2017-05-08 71 views
0

更新視圖我有這樣一個服務:角2陣列推不是從服務

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上的任何地方,然後任何後續附件添加顯示出來。

我在這裏錯過了什麼?

+0

你在哪裏調用'handleGoogleFiles'?你確定它是在角區內執行的嗎? – yurzui

+0

在視圖中,我已經調用了一個指令,如下所示:,此指令發出從Google Drive Picker中選擇文件時,方法句柄GoogleFiles成功接收來自此指令的數據 –

回答

1

你可以運行一個this.zone.run(()=> {});觸發重新繪製頁面。

區域被定義爲如下

公共區:NgZone

你不通過自身改變的變量,但改變變量的內容。它仍然在記憶中的同一個地方。此時,更改檢測有時會失敗。

+0

我按如下所示實現它:this.zone.run((=){this.attachments.push(attachment);} ); –

+0

我通常會這樣做 this.zone.run(()=> {}); this.attachments.push(attachment); –

+0

更多相反方向: this.attachments.push(attachment); this.zone.run(()=> {}); –