简体   繁体   中英

Angular - Return value as undefined

I have the following function:

  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);
    });
  }

When I try the following in onNgInit:

console.log(this.redirect());

It returns undefined. I'm not sure what to do to either be able to set a value to true or false to return true or false.

The function redirect doesn't return anything, right now. But it looks like you're working with a Promise. Try refactoring to return that 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);
    });
  }

So now you can print out the value when the promise resolves.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM