2017-02-21 48 views
0

我想在Angular 2中構建一個組件,該組件需要一個數據對象的數組,並且父組件的文件名將與數據創建一個csv文件並下載使用提供的文件名在瀏覽器中爲用戶提供文件。基本上,一個可重新使用的ExportCSV組件。 我有問題找到使用Observable完成此操作的正確方法。在子組件應該對其操作之前,需要由父組件在Rest API中檢索數據。父組件具有單獨的關聯服務來檢索數據。這些數據在服務器上分頁,導出應該包含整個結果集,而不僅僅是客戶端上的當前頁面。這強制需要在單擊導出按鈕時獲取整個結果集。 如果有人有這方面的經驗,請提供我應該如何完成這一任務的方向。提前致謝!如何獲取從一個角度組件到另一個異步數據

下面是相關代碼的一些片段:

的幾種方法
export class InvoiceListComponent { 
invoiceFullList: Observable<Array<Invoice>>; 
... 
setExportable(event: any) { 

    let params = new InvoiceSearchFilter(); 

    this._invoiceService.getAllInvoices(params) 
     .subscribe(
     (response: any) => { 
     this.invoiceFullList = response.json().data; 
     }, 
    () => { }); 
    } 
} 
<csv-export [dataList]="invoiceFullList | async" [fileName]='exportFileName'  (exportClickEvent)="setExportable($event)"></csv-export> 

export class CsvExportComponent { 
@Input() dataList: Array<any>; 
@Input() fileName: string = 'data-export'; 
@Output() exportClickEvent: EventEmitter<{}> = new EventEmitter(); 
... 
exportIt() { 
    this.exportClickEvent.emit(); 
    if (!this.dataList || this.dataList.length < 1) { 
     return false; 
    } 
    this.buttonEnabled = 'disabled'; 
    this.convertToCSV(this.dataList); 
} 
... 
} 
<button name="export-button" type="button" class="btn btn-primary btn-export" [disabled]='buttonEnabled' (click)="exportIt()">CSV Export</button> 
+1

請張貼代碼演示您嘗試來完成你試過了,什麼什麼,以及在哪裏失敗。 –

回答

1

一種是使用|async管。

父組件的模板

<child [someInput]="someObservable | async"></child> 
+0

管道'AsyncPipe'的無效參數'[object object],[object object],[object Object],[object Object],[object Object],[object Object]]' –

+0

對不起,沒有看到一些代碼不知道。 –

+0

'| async'只能與'Observable'或'Promise'一起使用。 'invoiceFullList'是沒有的。你的代碼的實際問題是什麼?如果你刪除'|來自您發佈的代碼的異步'應該可以正常工作。 –

0

一個快速的解決方案是使用ngIf,不使子組件除非有invoiceFullList數據:

<csv-export *ngIf="invoiceFullList" [dataList]="invoiceFullList" [fileName]='exportFileName' (exportClickEvent)="setExportable($event)"></csv-export> 

async管不在這種情況下可行,因爲invoiceFullList不是可觀察的。異步管道在您沒有手動訂閱時使用,因此異步管道會爲您執行此操作,但您正在訂閱請求並填充不能使用異步管道的數組。

0

我找到了一個可能感興趣的人的解決方案。我實現了OnChanges生命週期鉤在我的組件和ngOnChanges函數查找更改我的綁定數據像這樣:

ngOnChanges(changes: SimpleChanges) { 
    if (changes['dataList'] && this.dataList && this.dataList.length > 0) { 
     this.convertToCSV(this.dataList); 
    } 
} 
相關問題