【问题标题】:Calling firebase functions returns null调用 firebase 函数返回 null
【发布时间】:2020-06-03 14:22:33
【问题描述】:

我正在调用 Functions 函数来获取用户信息,但它返回 null。 请告诉我解决方案。

工作区/函数/src/index.ts

exports.getUser = functions.https.onCall((data, context) => {
  admin.database().ref(`user/${data.userId}`)
    .on('value', (snapshot) => {
      if (snapshot) return snapshot.val();
    });
});

workspace/src/app/sample.component.ts

firebase.functions().httpsCallable('getUser')({
  userId: profile.userId
}).then(data => {
  console.log(data);
}).catch(error => {
  alert(error);
});

【问题讨论】:

    标签: javascript angular firebase firebase-realtime-database google-cloud-functions


    【解决方案1】:

    首先,您应该使用once() 而不是on() 进行查询。 on() 设置了一个持久的监听器,这在 Cloud Functions 中并不好,因为它可能会泄漏监听器并花费你的钱。 once() performs a single query 并返回一个您可以使用的承诺。

    其次,您应该从您的函数返回一个承诺,该承诺使用您想要返回给客户端的数据进行解析。这是可调用类型触发器所必需的。现在,您没有从顶级函数返回任何内容。

    第三,您应该在函数的每个代码路径中返回一个值。

    exports.getUser = functions.https.onCall((data, context) => {
      return admin.database().ref(`user/${data.userId}`).once('value')
      .then(snapshot => {
        if (snapshot) {
          return snapshot.val();
        }
        else {
          // indicates that there was no data for the userId
          return null;
        }
      });
    });
    

    【讨论】:

      【解决方案2】:

      你没有在你的 https 调用中返回任何东西,添加一个返回:

      exports.getUser = functions.https.onCall((data, context) => {
        return admin.database().ref(`user/${data.userId}`)
          .on('value', (snapshot) => {
            if (snapshot) return snapshot.val();
          });
      });
      

      【讨论】:

      • 你的数据库user/${data.userId}中有这个路径吗?还有 console.log(snapshot.val()) 给你什么
      • 非常感谢。当我将“.once ('value')”更改为“.on ('value')”时,我能够收到它。
      猜你喜欢
      • 2020-08-15
      • 2020-06-03
      • 1970-01-01
      • 2021-10-16
      • 2018-11-24
      • 1970-01-01
      • 2021-03-04
      • 2019-02-27
      相关资源
      最近更新 更多