【问题标题】:Angular - Return value as undefinedAngular - 返回值未定义
【发布时间】:2017-12-12 03:43:52
【问题描述】:

我有以下功能:

  redirect() {
    this.afs.collection('links').doc(this.path).ref.get().then(function(doc) {
      if(doc.exists) {
        // define data and clicks
        var data = doc.data();
        var clicks = doc.data().clicks;
        // Update clicks
        doc.ref.update({
          'clicks': (clicks + 1)
        })
        .then(function() {
          if(data.landing == false) {
            // Redirect to url
            return false;
          } else {
            // Stay for Landing Page
            return true;
          }
        });
      } else {
        this.router.navigate(['/404']);
      }
    }).catch(function(error) {
      console.log("Error getting document:", error);
    });
  }

当我在 onNgInit 中尝试以下操作时:

console.log(this.redirect());

它返回未定义。 我不确定该怎么做才能将值设置为 true 或 false 以返回 true 或 false。

【问题讨论】:

  • 进行回调
  • @RandyStivenValentín 你能解释一下你的意思吗?老实说,我还在学习,对一切都不是很熟悉。

标签: javascript angular typescript angularfire2 angularfire5


【解决方案1】:

函数redirect 现在不返回任何内容。但看起来你正在使用 Promise。尝试重构以返回该承诺:

redirect() {

   return this.afs.collection('links').doc(this.path).ref.get().then(function(doc) {
      if(doc.exists) {
        // define data and clicks
        var data = doc.data();
        var clicks = doc.data().clicks;
        // Update clicks
        doc.ref.update({
          'clicks': (clicks + 1)
        })
        .then(function() {
          if(data.landing == false) {
            // Redirect to url
            return false;
          } else {
            // Stay for Landing Page
            return true;
          }
        });
      } else {
        this.router.navigate(['/404']);
      }
    }).catch(function(error) {
      console.log("Error getting document:", error);
    });
  }

所以现在您可以在 promise 解决时打印出该值。

this.redirect().then(value => console.log(value))

【讨论】:

  • 如果 data.landing 为假或真,我正在尝试专门返回真或假。或者将landing: boolean; 之类的值设置为真或假。我也尝试了你的建议,它仍然返回 undefined
猜你喜欢
  • 2021-04-27
  • 1970-01-01
  • 2019-10-19
  • 2017-01-08
  • 2018-07-21
  • 2019-07-28
  • 2017-10-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多