2016-11-04 39 views
0

我正在創建一個服務,在ngAfterViewInit中完成數據的獲取。如何將數據從一個生命週期鉤子傳遞到另一個生命週期

export class AppComponent {  
    gameData:any; 
    constructor(private _AppComponentService: AppComponentService) {} 

    ngOnInit(){ 
     this._AppComponentService.getGameData().subscribe(x => { 
      this.gameData = x; 
     }); 
    } 

    ngAfterViewInit() { 
     console.log(this.gameData); //Undefined 
    } 
} 
+2

最有可能的,因爲GAMEDATA還沒有準備好。如果在afterViewInit函數中需要gameData,則可以將服務調用移至該函數。 – Sefa

+0

如果我在afterviewinit中移動呼叫,它仍然是未定義的。 – fruitjs

+0

@fruitjs如果你在console.log之外的訂閱當然你仍然會得到undefined,因爲getGameData()是一個異步函數。你能證明你如何使用它? – echonax

回答

2

由於.getGameData()可能是一些異步調用那麼當ngAfterViewInit被稱爲this.gameData屬性沒有價值,因爲.subscribe()回調沒有被調用呢。

如果你想使用觀測量爲此,您可以做gameData一個ReplaySubject或訂閱.getGameData()兩個的LiveCycle鉤:

  1. 製作gameData一個ReplaySubject

    export class AppComponent {  
        gameData: ReplaySubject = new ReplaySubject(1); 
        constructor(private _AppComponentService: AppComponentService) {} 
    
        ngOnInit(){ 
         this._AppComponentService.getGameData().subscribe(x => { 
          this.gameData.next(x); 
         }); 
        } 
    
        ngAfterViewInit() { 
         this.gameData.subscribe(val => console.log(val)); 
        } 
    } 
    

隨着ReplaySubject即使訂閱,ngAfterViewInit()也會收到一個值s後this.gameData.next(x)發出的價值。

  • 訂閱.getGameData()兩次:

    export class AppComponent {  
        observable: Observable; // or EventEmitter depending on what you used in getGameData() 
        constructor(private _AppComponentService: AppComponentService) {} 
    
        ngOnInit(){ 
         this.observable = this._AppComponentService.getGameData(); 
         this.observable.subscribe(x => { 
          // whatever you need 
         }); 
        } 
    
        ngAfterViewInit() { 
         this.observable.subscribe(val => console.log(val)); 
        } 
    } 
    
  • +0

    感謝馬丁的幫助。 – fruitjs