2016-11-04 91 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