Angular 5 @Input总是在ngOnInit()上未定义

时间:2018-06-17 17:49:49

标签: angular firebase

我正在使用角度火力计应用,但我不知道如何解决问题。 我的@Input总是在我的ngOnInit()上未定义,但我必须使用此Input值初始化。

  

错误类型错误:无法读取属性'长度'未定义的

我尝试添加* ngIf,因为我在类似的帖子中看到或初始化我的房间,但没有任何工作。我是否必须使用超时或有更好的方法吗?

以下是详细信息:

玩家组件:

@Input() room: Room;
    players: Player[];
    playersSubscription: Subscription;

    constructor(private playerService: PlayerService, private router: Router) { }

    ngOnInit() {
        this.playersSubscription = this.playerService.playersSubject.subscribe(
            (players: Player[]) => {
                this.players = players;
            }
        );

        this.playerService.getPlayersRoom(this.room.players);

        this.playerService.emitPlayers();

    }

HTML:

<div *ngIf="room">
    <ul>
        <li *ngFor="let p of room.players">{{p}}</li>
    </ul>
</div>
usernames:
<div *ngIf="players">
    <ul>
        <li *ngFor="let player of players">
            {{player.username}} // This will not works
        </li>
    </ul>
</div>

服务:

    getPlayersRoom(ids: string[]) {

        while (ids.length > 0) {
            var id = ids.splice(0, 1)[0];
            firebase.database().ref('/users/').child(id).once('value', function (snapshot) {
                this.players.push(snapshot.val());
            });
        }
        this.emitPlayers();
}

室:

room: Room;

constructor(private router: Router,
    private route: ActivatedRoute,
    private roomService: RoomService
) { }

ngOnInit(): void {
    this.room = new Room();
    const id = this.route.snapshot.params['id'];
    this.roomService.getRoom(+id).then(
        (room: Room) => {
            this.room = room;
        }
    );
}

HTML:

<div *ngIf="room">
        Room n°{{room.id}} + password {{room.password}}
    <h1>PLAYERS room</h1>
    <div *ngFor="let p of room.players">
        {{p}}
    </div>
    Players:
    <app-players *ngIf="room" [room]="room"></app-players>
    end
</div>

编辑: 问题出在ngOnInit(播放器组件):此时@Input未定义(然后它正在执行getPlayersRoom(未定义))。有人在想吗?无法在构造函数/ ngoninit中使用@Input?那我该怎么做呢?

2 个答案:

答案 0 :(得分:0)

此处有肠道响应,但看起来roomService.getRoom(+id)是异步的,这意味着根据初始化new Room()时发生的情况,当您的孩子出现时,该属性可能仍为undefined组件已初始化。

编辑:在反思中,也许您只需要预先将数组属性声明为空数组:

players: Player[] = []

答案 1 :(得分:0)

我找到了替代解决方案:

服务:

getPlayersRoom(ids: string[]) {

        for(let i=0;i<ids.length;i++){
            this.getPlayer(ids[i]).then(
                (player: Player) => {
                    if(player){
                       this.players.push(player);
                    }
                }
            );

        }
        this.emitPlayers();
}

组件: 我实现了OnChanges,然后:

ngOnChanges(){

        if(Object.keys(this.room).length>0){
            this.playerService.getPlayersRoom(this.room.players);
        }
    }

我认为这不是最好的方法,但至少可以正常工作。