У меня есть Firebase Auth ID, как мне использовать его в списке БД? - PullRequest
0 голосов
/ 06 мая 2018

Я использовал

fAuth.authState.subscribe( user => {
  if (user) { this.userId = user.uid }
});

однако сейчас я пытаюсь выполнить поиск внутри userProfile по идентификатору, чтобы получить значение в баллах.

getTotalPoints(){
  this.db.list('/userProfile/' + this.userId).valueChanges().subscribe(
    data => {
      console.log(JSON.stringify(data))
      this.pointsValue = data;
    }
  )
}

Я получаю ошибку

Ошибка выполнения

Uncaught (в обещании): Ошибка: Ошибка Reference.child: Первый аргумент был неверным путем = "/ userProfile / [объект Объект]". Пути должны быть непустыми строками и не могут содержать ".", "#", "$", "[" Или "]" Ошибка: сбой Reference.child: первый аргумент был неверным путем = "/ userProfile / [Объект Object]". Пути должны быть непустыми строками и не должны содержать ".", "#", "$", "[" Или "]" в Object.exports.validatePathString

Извините, если ответ прост, очень плохо знаком с этим.

Вот DB

Полный код страницы

import { Component, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams, LoadingController } from 'ionic-    angular';
import { AngularFireAuth } from 'angularfire2/auth';
import { AngularFireDatabase, AngularFireList } from 'angularfire2/database';
import 'rxjs/add/operator/map';

@IonicPage()
@Component({
  selector: 'page-dashboard',
  templateUrl: 'dashboard.html',
})

export class DashboardPage {

  pointsValue: {}

  userId = {}

  tasks:Array<any> = [];


  constructor(public navCtrl: NavController, public navParams: NavParams, public db: AngularFireDatabase, public afAuth: AngularFireAuth, public loadingCtrl: LoadingController) {


    afAuth.authState.subscribe( user => {
      if (user) { this.userId = user.uid }
    });

    this.getTotalPoints()

     this.tasks = [
      { 
      name: 'Clean bedroom', 
      status: '100' 
      },
      { 
      name: 'Empty dishwasher', 
      status: '100' 
      },
      { 
      name: 'Take dog for a walk', 
      status: '100' 
      },
    ];

  }

  checkUser() {
    console.log(this.userId);
  }

  getTotalPoints(){
    this.db.list('/userProfile/' + this.userId).valueChanges().subscribe(
      data => {
        console.log(JSON.stringify(data))
        this.pointsValue = data;
      }
    )
  }
}

Ответы [ 2 ]

0 голосов
/ 06 мая 2018

База на ошибку

Первый аргумент был неверным путем = "/ userProfile / [объект объекта]"

userId = {} //is an object, where it should be a non-object data type

А в вашем коде

 //You're doing a async method
 afAuth.authState.subscribe( user => {
      if (user) { this.userId = user.uid }
    });
 /*After that you called your method, which caused userId 
 to be an object since you initialized it as an empty object */
 this.getTotalPoints()

Для лучшей реализации сделайте это так

//Set userId as null
userId: any = null

Сделать эту функцию иметь параметр userId

 getTotalPoints(id: any){
    this.db.list('/userProfile/' + id).valueChanges().subscribe(
      data => {
        console.log(JSON.stringify(data))
        this.pointsValue = data;
      }
    )
  }

тогда в вызове подписки сделай это так

afAuth.authState.subscribe( user => {
      if (user) { 
          this.userId = user.uid 
          this.getTotalPoints(this.userId);
       }
    });
0 голосов
/ 06 мая 2018

Вы используете объект вместо списка, если хотите получить данные Firebase Object

getTotalPoints(){
this.db.object('/userProfile/' + this.userId).valueChanges().subscribe(
  data => {
    console.log(JSON.stringify(data))
    this.pointsValue = data;
  }
)

Больше информации в документации AngularFire2: https://github.com/angular/angularfire2/blob/master/docs/rtdb/objects.md

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...