首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >速记if-else在Javascript中返回错误

速记if-else在Javascript中返回错误
EN

Stack Overflow用户
提问于 2018-12-13 08:35:26
回答 2查看 50关注 0票数 0

下面这行JS代码并没有像我预期的那样工作。

当imageUrl有一个值时,我得到下面的错误,我希望notificationBody = "You received a new image message“。

这里我漏掉了什么?

"notification.body“属性的

值无效。值必须是字符串。

代码语言:javascript
复制
const notificationBody = (imageUrl === "" ? "You received a new image message." : messageTxt)

消息负载:

代码语言:javascript
复制
const payload = {
            notification: {
              title: senderName + " sent you a message",
              body: notificationBody
            },

整个函数:

代码语言:javascript
复制
exports.notifyNewMessage = functions.database.ref('/messages/{pushId}').onCreate((snap, context) => {

  const messageSnap = snap.val(); //snap.after.val();

  const fromId = messageSnap.fromId; 
  const toId = messageSnap.toId; 
  const messageTxt = messageSnap.message; 
  const imageUrl = messageSnap.imageUrl; 

  console.log('fromId: ', fromId);
  console.log('message: ', messageTxt);

  // Get the list of device notification tokens.
  const getDeviceTokensPromise = admin.database().ref('/fcmtokens/' + toId + '/registrationtokens').once('value');

  console.log('getDeviceTokensPromise', getDeviceTokensPromise);


  return admin.database().ref('/fcmtokens/' + toId + '/registrationtokens').once('value').then((userTok) => {

    const registrationTokens = Object.keys(userTok.val())

    console.log('registrationTokens', registrationTokens);


    return admin.database().ref('/users/' + fromId).once('value').then((userDoc) => {

      const user = userDoc.val(); //snap.after.val();

      const senderName = user.firstName //'Vanessa' //userDoc.firstName //get('firstName')
      console.log('senderName: ', senderName);

      const notificationBody = (imageUrl === "" ? "You received a new image message." : messageTxt)

      console.log('imageUrl: ', imageUrl);
      console.log('messageTxt: ', messageTxt);
      console.log('notificationBody: ', notificationBody);

        //build media messages notification
        const payload = {
            notification: {
              title: senderName + " sent you a message",
              body: notificationBody
            },
            data: {
              SENDER_NAME: senderName,
              SENDER_ID: fromId

            }//end data
        }//end payload

        //send message
        return admin.messaging().sendToDevice(registrationTokens, payload).then( response => {

          const stillRegisteredTokens = registrationTokens

          response.results.forEach((result, index) => {

                    const error = result.error

                    if (error) {

                        const failedRegistrationToken = registrationTokens[index]

                        console.error('blah', failedRegistrationToken, error)

                        if (error.code === 'messaging/invalid-registration-token' || error.code === 'messaging/registration-token-not-registered') {

                                const failedIndex = stillRegisteredTokens.indexOf(failedRegistrationToken)

                                if (failedIndex > -1) {
                                    stillRegisteredTokens.splice(failedIndex, 1)
                                }

                            }
                    }

                })//end forEach

                var  validTokens = {};

                stillRegisteredTokens.forEach(function(element){
                  console.log('valid token: ', element);
                  validTokens[element] = true;
                });
                //updates['registrationtokens'] = stillRegisteredTokens; ....update(updates);

                return admin.database().ref('fcmtokens/' + toId + '/registrationtokens').set(validTokens)

                // return admin.database().ref("fcmtokens/" + toId).update({
                //     //registrationTokens: stillRegisteredTokens
                // })//end update

        })//end sendToDevice


    })//end return-then

  })//end return-then

});
EN

回答 2

Stack Overflow用户

发布于 2018-12-13 08:42:23

首先,看起来如果imageUrl不是"“,那么notificationBody将是messageTxt的值,而不是"You received a new image message”。字符串。

javascript的三元语句是这样工作的:

代码语言:javascript
复制
const foo = (<conditional> ? <value if conditional is True> : <value if conditional is False>)

其次,您确定您的示例代码与您得到错误的代码完全相同吗?我在您的示例中看不到对notification.body的引用。

票数 2
EN

Stack Overflow用户

发布于 2018-12-13 08:47:39

您的三元组没有执行预期的操作,第一种情况表示true,第二种情况表示false,因此您可以切换大小写,或者在我下面的解决方案中,将比较运算符切换为!==

我怀疑您的代码中发生了什么,因为您的三元组是不正确的,您没有为messageTxt设置值,所以它将undefined作为body的值传递到您的payload

我也强烈建议你在payload中使用JSON.stringify(),如果你还没有这么做的话。

解决方案

代码语言:javascript
复制
const senderName = 'tacocat';
const imageUrl = 'something';
const messageTxt = 4815162342

const notificationBody = (
  imageUrl !== "" ?
  "You received a new image message." :
  messageTxt
)

const payload = JSON.stringify({
  notification: {
    title: senderName + " sent you a message",
    body: notificationBody
  }
})
console.log(payload)

文档

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53753414

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档