Angular 5 with Firebase - 服务在服务完成之前返回组件中的undefined

时间:2018-02-25 04:31:08

标签: angular angularfire2 angular-services

我有一项服务应该返回角色的一些统计数据。

统计数据是根据角色等级计算的。

父组件正在调用服务,该服务调用Firebase来查找级别,然后订阅以查看值并进行计算,但父级看到currentStats仍未定义。我觉得我需要告诉父组件等待并可能通过生命周期钩子来解决这个问题,但这似乎有点草率,我想知道这样的事情的最佳实践是什么。任何指针都会受到欢迎。代码如下:

家长TS:

Snapchat

服务:

Snapchat

1 个答案:

答案 0 :(得分:1)

如果您不希望它被定义,您需要立即创建Observable。试试那个

// level service returns the character level
constructor(private levelService: levelService) {
    // Services do not utilize the oninit lifecycle, so I wrote a function to act like one.
    // I saw this as a suggestion in researching but this does not seem optimal.
    this.init();
}

levelObservable: any;
level: number;
characterSp: number;
characterVitality: number;
statsSource : Subject<any> = new Subject<any>();
currentStats: Observable<any> = this.statsSource.asObservable();

init(){
    this.levelObservable = this.levelService.getLevel();
    this.levelObservable.subscribe(level => {
        this.level = level;
        this.characterSp = this.level * 2;
        this.characterVitality = this.level * 6;
        this.statsSource.next({
            spellPoints: this.characterSp,
            actionDice: 3,
            vitality: this.characterVitality,
            wounds: 10 
        });
    });

编辑:关于如何使用异步管道的示例

<强> component.ts

constructor(private statsService: StatsService...) {}

statsSource$: Observable<any>;

ngOnInit() {
    this.statsSource$ = this.statsService.currentStats;

}

<强> component.html

<span>{{(statsSource$ |async)?.vitaliy}}}}