0

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.

Gurgen Grigoryan
  • 265
  • 1
  • 5
  • 17

1 Answers1

0

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))
Brendan Whiting
  • 494
  • 3
  • 13
  • I'm trying to specifically return true or false, if data.landing is false or true. Or set a value like `landing: boolean;` to true or false. I also tried what you proposed and it still returned undefined – Gurgen Grigoryan Dec 12 '17 at 04:11