【问题标题】:Angular 5 show data from firebase nodesAngular 5 显示来自 firebase 节点的数据
【发布时间】:2018-02-11 00:52:16
【问题描述】:

我需要一点帮助。 我正在尝试显示来自特定登录用户的数据,但我很难。

在 html 中:

<div *ngFor="let to of UnData">

TS:

export class something {
  todo: AngularFireList<any>;
  UnData = [];
  userId: string;

  constructor(public navCtrl: NavController, public navParams: NavParams, private db: AngularFireDatabase, private fire: AngularFireAuth) {
    this.fire.authState.subscribe(user =>{
      if(user) this.userId = user.uid      
    });

    if (!this.userId) return;

    this.db.list("people/${this.userId}").valueChanges().subscribe(_data => {
      this.UnData = _data;
      console.log(this.UnData);
    });
  }

console.log 没有给我任何回报。我认为我在从数据库获取数据的代码中做错了。请给我一点帮助:-)

【问题讨论】:

  • 你会想要使用反引号来获取 ES6 字符串模板,所以this.db.list(`people/${this.userId}`)
  • 我刚刚发现,如果我像“sdfsrgcstcrthjyxcyxcyyfe”这样的普通用户 ID 写出我可以访问数据:this.db.list(people/user id goes here).valueChanges().subscribe(_data = > { this.UnData = _data; console.log(this.UnData); });但是当我使用 ${this.userId} 时,什么也没有发生,你 console.log(this.userId) 返回我有效的用户 ID
  • 那是因为您使用的是纯字符串语法,并且期望它的行为类似于template literal。要么使用我的第一条评论中显示的反引号,要么使用简单的字符串连接this.db.list("people/"+this.userId)

标签: javascript angular firebase-realtime-database


【解决方案1】:

感谢弗兰克, 第一个问题是反引号,但我仍然有问题并已解决,重要的部分是 ngOnInit(userId:string):

export class something {
  todo: AngularFireList<any>;
  unData = [];
  userId: string;
  title: string;
  desc: string;

  constructor(public navCtrl: NavController, public navParams: NavParams, private db: AngularFireDatabase, private fire: AngularFireAuth) {
    this.fire.authState.subscribe(user => {
      if (user) {
        this.userId = user.uid;
        console.log(this.userId);
      }
    });

  }
  postDatatoDB(title: string, desc: string, userId: string): void {
    this.db.list("/tasks/" + this.userId).push({ title: title, desc: desc });
    this.title = '';
    this.desc = '';
  }


  **ngOnInit(userId:string)** {

    this.db.list<any>(`/tasks/${this.userId}`).valueChanges().subscribe(data => {
      this.unData = data;
        console.log(this.unData);
      });

  }

}

【讨论】:

    猜你喜欢
    • 2016-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-13
    • 2018-06-12
    • 2018-10-02
    • 2019-12-20
    • 2021-12-03
    相关资源
    最近更新 更多