无法读取未定义Angular 2的属性

好饼

我正在尝试做一个简单的导入,但是我遇到了一个巨大的堆栈跟踪问题。

我曾尝试到处搜索与此相关的问题,但对我而言,堆栈跟踪没有提供太多信息。

编辑:我尝试将其设置为一个不是从Firebase提取的变量,它工作正常。我想现在的问题是如何处理Firebase中的此信息,以便在准备就绪时加载它。

以下是相关文件:

main.ts:

import { bootstrap }    from '@angular/platform-browser-dynamic';
import {AppComponent} from './app.component';
import { HTTP_PROVIDERS } from '@angular/http';

bootstrap(AppComponent, [HTTP_PROVIDERS]);

player.services.ts:

import { Injectable } from '@angular/core';
import {Player} from "../classes/player";


@Injectable()
export class PlayerService {

    player: Player;

    getPlayer()
    {
        return Promise.resolve(this.player);
    }

    createPlayer(uid: string, name: string, firebaseRef: Firebase)
    {
        this.player = {
            'uid': uid,
            'name': name,
            'level': 1,
            'maxHealth': 100,
            'health': 100,
            'maxEnergy': 50,
            'energy': 50,
            'fun': 1,
            'skill': 1,
            'knowledge': 1
        }

        firebaseRef.child('players').child(uid).set(this.player);
    }

    setPlayer(player: Player)
    {
        this.player = player;
    }
}

app.component.ts

import { Component, OnInit } from '@angular/core'
import { PlayerDetailComponent } from './components/player-detail.component';
import {PlayerService} from "./services/player.service";
import {FirebaseEventPipe} from "./firebasepipe";
import {Player} from "./classes/player";

@Component({
    selector: "my-app",
    templateUrl: 'app/views/app.component.html',
    directives: [PlayerDetailComponent],
    providers: [PlayerService],
    pipes: [FirebaseEventPipe]
})

export class AppComponent implements OnInit{
    title = "title";

    authData: any;

    private firebaseUrl: string;
    private firebaseRef: Firebase;

    private loggedIn = false;
    player: Player;

    constructor(private playerService: PlayerService) {
        this.firebaseUrl = "https://!.firebaseio.com/";
        this.firebaseRef = new Firebase(this.firebaseUrl);
        this.firebaseRef.onAuth((user) => {
            if (user) {
                this.authData = user;
                this.loggedIn = true;
            }
        });
    }

    getPlayer() {
        this.firebaseRef.once("value", (dataSnapshot) => {
            if (dataSnapshot.child('players').child(this.authData.uid).exists()) {
                this.firebaseRef.child('players').child(this.authData.uid).once("value", (data) => {
                    this.player = data.val();
                    this.playerService.setPlayer(this.player);
                    console.log(this.player);
                });
            } else {
                this.playerService.createPlayer(this.authData.uid, this.getName(this.authData), this.firebaseRef);
                this.playerService.getPlayer().then(player => this.player);
                console.log(this.player);
            }

        });




    }

    ngOnInit() {
        this.getPlayer();
    }

    authWithGithub() {
        this.firebaseRef.authWithOAuthPopup("github", (error) =>
        {
            if (error) {
                console.log(error);
            }
        });
    }

    authWithGoogle() {
        this.firebaseRef.authWithOAuthPopup("google",(error) =>
        {
            if (error) {
                console.log(error);
            }
        });

    }

    getName(authData: any) {
        switch (authData.provider) {
            case 'github':
                return authData.github.displayName;
            case 'google':
                return authData.google.displayName;
        }
    }
}

玩家细节组件

import { Component, Input, OnInit } from '@angular/core';
import { Player } from '../classes/player';


@Component({
    selector: "player-details",
    templateUrl: "app/views/player-detail.component.html",
    styleUrls: ['app/style/player-detail.component.css'],
})

export class PlayerDetailComponent implements OnInit{
    @Input() player: Player;

    ngOnInit() { console.log(this.player)}
}

app.component.html

<nav class="navbar navbar-default">
    <div class="container">
        <ul class="nav navbar-nav">
            <li class="navbar-link"><a href="#">Home</a></li>
        </ul>
    </div>
</nav>

<div class="jumbotron" [hidden]="loggedIn">
    <div class="container">
        <h1>Angular Attack Project</h1>
        <p>This is a project for the <a href="https://www.angularattack.com/">Angular Attack 2016</a> hackathon. This is a small project where set goals
            in order to gain experience as a player and person. In order to begin, please register with on of the following services</p>
        <button class="btn btn-social btn-github" (click)="authWithGithub()"><span class="fa fa-github"></span>Sign Up With Github </button>
        <button class="btn btn-social btn-google" (click)="authWithGoogle()"><span class="fa fa-google"></span>Sign Up With Github </button>
    </div>
</div>


<player-details [player]="player" [hidden]="!loggedIn"></player-details>

player-detail.component.html

<div id="player" class="panel panel-default">
    <div id="player-stats" class="panel-body">
        <img id="player-image" class="img-responsive" src="../app/assets/images/boy.png"/>
        <div class="health-bars">
            <div class="health-bar">HEALTH:<br/><progress value="{{ player.health }}" max="{{ player.maxHealth }}"></progress></div>
            <div class="energy-bar">ENERGY:<br/><progress value="{{ player.energy }}" max="{{ player.maxEnergy }}"></progress></div>
            <div class="player-attributes"><span class="fa fa-futbol-o player-attr fun">: {{ player.fun }} </span><span class="fa fa-cubes player-attr skill">: {{ player.skill }}</span> <span class="fa fa-graduation-cap player-attr knowledge">: {{ player.knowledge }}</span></div>
        </div>
    </div>
</div>
好饼

PlayerDetailComponent载入时,播放器变量未定义,因此没有播放器之类的对象。

为了解决这个问题,OnChanges可以这样实现:

import { Component, Input, OnChanges, SimpleChange } from '@angular/core';
import { Player } from '../classes/player';
import {HealthBarComponent} from "./health-bar.component";
import {ChecklistComponent} from "./checklist.component";


@Component({
    selector: "player-details",
    templateUrl: "app/views/player-detail.component.html",
    styleUrls: ['app/style/player-detail.component.css'],
    directives: [HealthBarComponent, ChecklistComponent],
})

export class PlayerDetailComponent implements OnChanges{

    @Input()
    player: Player;

    ngOnChanges(changes: {[propName: string]: SimpleChange}) {
    }


}

然后我们可以*nfIf="player"在模板中添加以确保播放器对象在加载元素之前不为空。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Angular无法读取未定义的属性

无法读取未定义 Angular 的属性

无法读取Angular 2中未定义的属性“错误”?

Angular 2`无法读取未定义的属性'dataService'

Angular2:无法读取未定义的属性“名称”

无法读取未定义的属性“ post”-Angular 2

Angular2无法读取未定义的属性“ push”

无法读取未定义[Angular2]的属性“ isStopped”

Angular 2 TypeError:无法读取未定义的属性“ toUpperCase”

无法读取未定义angular2的属性

Angular - Ionic 2 - 无法读取未定义的属性“订阅”

Angular 2+无法读取未定义的属性“ id”

Angular 2-无法读取未定义的属性“ ...”

Angular 2-无法读取未定义的属性“ get”(http未定义)

无法在 Angular 中读取未定义的属性(读取“订阅”)

无法读取未定义读取“deletePostById”Angular 的属性

无法读取未定义的属性(读取“updateLicence”)Ionic Angular

Angular 2无法读取未定义类型的属性“ subscribe”:无法读取未定义的属性“ subscribe”

“无法读取未定义的属性‘推送’”Angular 9 组件

无法读取未定义的属性“ NullLogger”(Angular / CLI 1.4.7)

Angular TypeError无法读取未定义的属性“ then”

highcharts-angular:无法读取未定义的属性“ chart”

Angular 6:无法读取未定义的属性“ get”

Angular无法读取未定义的属性“ navigate”

无法读取未定义的属性“ healthCarePlans”(Angular5)

Angular4无法读取未定义的属性“列表”

无法使用 Angular 6 读取未定义的属性“冠军”

无法使用Angular读取未定义的属性“ get”

NativeScript/Angular - TypeError:无法读取未定义的属性“符号”