2017-08-02 94 views
1

我正在訂閱正在製作和API調用的方法。所述訂閱體內,我指定(分配所述第一時間和修改對象第二次)接收到的數據的一個對象按照以下方式:在模板中呈現數據之後調用函數:Angular2

this.serviceObj.getData() 
    .subscribe(
    data => { 
    this.DataObj = { 
     ..... some content ..... 
    } 
    this.anotherFunction(); 
    }, 
    error => { 
    console.log('error'); 
    }, 
); 

在訂閱體,一旦我接收數據,我將它分配給「DataObj」,在DataObj獲得新數據後,它將在UI中呈現。我希望「anotherFunction()」在「dataObj」被分配新數據之後執行,並在UI中呈現。但是看起來數據正在成功分配,但在UI中成功呈現新數據之前,「anotherFunction()」正在執行。

我試着使用:

ngAfterViewChecked() { 
    this.anotherFunction(); 
} 

的「anotherFunction()」如果我把它放在ngAfterViewChecked()內的視圖改變後得到執行,但這樣下去執行,即使有一個微小的變化模板,但我只希望它在「DataObj」更改時運行。

任何建議如何使這項工作有效? (不經常使ngAfterViewChecked()被執行)。

+0

你試過'ngOnChanges'? –

+0

我試過這樣做,@JasonSpradlin。但是閱讀Angular關於ngOnChanges的文檔,它說:「當指令的任何數據綁定屬性發生變化時所調用的生命週期鉤子。」所以當我收到數據時,ngOnChanges沒有被執行。 – Aiguo

回答

1

想到的唯一的東西就是基於「信號量」的方法。將標誌dataReceived設置爲false。在.subscribe中,將其設置爲true。然後在ngAfterViewChecked()只運行代碼,如果dataReceived爲真。

ngAfterViewChecked() { 
    if (this.dataRetrieved) { 
    this.anotherFunction(); 
    this.dataRetrieved = false; 
    } 
} 

我不喜歡「基於標誌」的方法。但這是解決這個問題的唯一想法。也許別人有更好的解決方案?

+0

我現在正在那樣做。但正如你所說,不是最好的方法。但謝謝你的回答:) – Aiguo

0

管道怎麼樣?

它運行權之前渲染,你將能夠調用anotherFunction

import { Pipe, PipeTransform } from '@angular/core'; 

@Pipe({name: 'anotherFunction'}) 
export class AnotherFunctionPipe implements PipeTransform { 

    transform(value: any): number { 

    anotherFunction(); 

    return value; 
    } 

    anotherFunction() { 
    // do something 
    } 

} 

用法是這樣的

<div> {{ DataObj | anotherFunction }} </div>