如何在用户登录后更新firebase-query

时间:2017-12-05 22:48:26

标签: firebase-realtime-database firebase-authentication polymer-2.x polymerfire

使用聚合物和firebase我有一些只能由登录用户访问的数据。但是,当用户登录应用程序时,数据不会自动更新。

一种简单的解决方法是强制使用location.reload()重新加载页面。但是,我正在尝试发现如何在不重新加载整个应用程序的情况下更新这些值。有什么想法吗?

预期结果:

当用户登录时,所有fibase-documentfirebase-query都会更新已同步的数据。

实际结果:

这些元素不会更新,用户必须重新加载页面

示例:

元素:app-auth.html

<firebase-app
  id="firebaseApp"
  auth-domain="app.firebaseapp.com"
  database-url="https://app.firebaseio.com"
  storage-bucket="app.appspot.com"
  api-key="api"
  messaging-sender-id="id"
 ></firebase-app>

<firebase-auth id="auth"
  signed-in="{{isUserLogged}}"
  user="{{user}}"
  on-error="_onAuthError"
  log
></firebase-auth>

login(credentials) {
    if (credentials.provider === 'email') {
      this.$.auth.signInWithEmailAndPassword(credentials.params.email, credentials.params.password)
        .catch(e => {
          if (e.code === 'auth/user-not-found') {
            this.$.auth.createUserWithEmailAndPassword(credentials.params.email, credentials.params.password)
              .then(this._successfulLogin());
          }
        })
        .then(this._successfulLogin());
      this.password = null;

    } else {
      this.$.auth.signInWithPopup(credentials.provider);
    }
  }

app-contents.html

   <firebase-query
        data="{{contents}}"
        path="/contents"
    ></firebase-query>

    <div class="card">
        <h1>Contents:</h1>
        <template is="dom-repeat" items="[[contents]]" as="content">
            <app-content-preview="[[content]]"></app-content-preview>
        </template>
    </div>
</template>

内容元素显示用户必须回答的问卷,以便完成应用的目标。但是,调查问卷只能由登录用户访问。我想,当用户登录app-auth时,处理他的身份并更新firebase-query,显示他必须回答的问卷

1 个答案:

答案 0 :(得分:1)

实际上应该在查询时读取数据(由于你的firebase数据库规则。(如果允许全部读取,但是在登录时写入)类似于数据库规则;

import numpy as np
np.fill_diagonal(correlation_matrix, 0)

但是如果让我们说读也需要auth!= null,让我们改变你的代码:

"rules": {
    ".read": true,
    ".write": "auth != null"
     }

并定义一个像

这样的观察者
 <firebase-query
        data="{{contents}}"
        path="{{pathContents}}"
    ></firebase-query>

此观察者将检查用户是否存在。如果存在,则路径将被定义为static get observers() { return ['_isUserLogged(user)'] _isUserLogged(user) { if (user) { this.set('pathContents', 'contents'); } } ,而查询元素将自动再次触发。 希望这会奏效:)

另一个contents选项是;

js

请注意:如果您使用上述代码读取数据库,则不需要_isUserLogged(user) { if (user) { var db = firebase.database(); db.ref('contents').on('value', snapshot=>{ if (snapshot.exists()) { //To check that you have a data this.set('contents', snapshot.val() ); } }) } } 元素。所以,删除它。