【问题标题】:ionic framework append data to array离子框架将数据附加到数组
【发布时间】:2018-04-24 10:21:35
【问题描述】:
firedata = firebase.database().ref('/chatusers/');    
postData(val){    
items=[];
this.items.push(val);
      this.firedata.child(this.afireauth.auth.currentUser.uid).update({
        uid: this.afireauth.auth.currentUser.uid,
        post: this.items,
        displayName: this.afireauth.auth.currentUser.displayName
      })
 })

我正在尝试将我的数据推送到 Firebase,所以每次调用 postData 函数时,我都希望我的数组 items=[] 继续附加数据 val。 目前它只是用新值覆盖。 我是ionic3 的新手,所以请帮助我。

expected output:
---post
      0: 'A'
      1: 'B'
      2: 'C'
uid:
-----------------------------------------------

Code with ionic3 storage


    firedata = firebase.database().ref('/chatusers/');    
        postData(val){
    var uniqueUID = this.afireauth.auth.currentUser.uid;

    let toaster = this.toastCtrl.create({
      duration: 3000,
      position: 'bottom'
    });

    if(this.userdata.title==""){
      toaster.setMessage("Please fill out the title");
      toaster.present();
    }

    this.storage.get('Task1-'+uniqueUID).then((item)=> {
      if (item != null) {
        item.push(val);
        this.storage.set('Task1-'+uniqueUID, item);
      }
      else {
        let array = [];
        array.push(val);
        this.storage.set('Task1-'+uniqueUID, array);
      }
      this.items.push(val);
      this.firedata.child(this.afireauth.auth.currentUser.uid).update({
        uid: this.afireauth.auth.currentUser.uid,
        post: item,
        displayName: this.afireauth.auth.currentUser.displayName
      })

    })

  }
}

【问题讨论】:

    标签: angular typescript ionic-framework ionic2 ionic3


    【解决方案1】:

    如下图在myMethod()外声明即可。

    items:any=[];
    
    constructor(){
    
    }
    
    myMethod(){
    
        firedata = firebase.database().ref('/chatusers/');    
        postData(val){    
    
        this.items.push(val);
          this.firedata.child(this.afireauth.auth.currentUser.uid).update({
            uid: this.afireauth.auth.currentUser.uid,
            post: this.items,
            displayName: this.afireauth.auth.currentUser.displayName
          })
     })
    }
    

    【讨论】:

    • 不起作用。所以基本上当我将选项卡切换到其他选项卡时,它只会覆盖。没有按照我在 firebase 中的要求以列表方式添加。
    • 哦..你没有告诉页面移动不是吗?您需要为此使用 Ionic Storage 模块。如果您需要更多帮助,请查看并告诉我:ionicframework.com/docs/storage
    • 我做了存储部分,它确实有效,但我遇到的问题是所有用户都存储了相同的数据。我已经发布了离子存储的代码。检查
    • 那么你需要按照user这样保持dynamic key这样:this.storage.set('Task-'+ userId, array);。就是这样。
    • 是这样想的。工作!有一个疑问,我无法在 firebase 上看到我的数组 [0],但是当我发布另一篇帖子时,它会显示为数组 [1] 和数组 [0]。为什么会这样?
    猜你喜欢
    • 2018-07-03
    • 1970-01-01
    • 1970-01-01
    • 2018-10-13
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    • 1970-01-01
    • 2018-02-13
    相关资源
    最近更新 更多