如何将数据从一个Lifecycle hook传递到另一个

时间:2016-11-04 10:35:58

标签: angular rxjs

我正在创建一个服务,以便在完成后获取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
    }
}

1 个答案:

答案 0 :(得分:2)

由于.getGameData()可能是一些异步调用,因此当ngAfterViewInit被调用时,this.gameData属性没有值,因为.subscribe()的回调尚未被调用。< / p>

如果你想为此使用Observables,你可以在{28}中使gameData成为ReplaySubject或订阅.getGameData()

  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));
        }
    }
    
  2. 使用ReplaySubject ngAfterViewInit()即使在this.gameData.next(x)发出值后订阅,也会收到一个值。

    1. 订阅.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));
          }
      }