U rock
U rock

Reputation: 775

Navigate page upon condition

I have to navigate page based upon condition, here I get response from my backend and when I try to evaluate this it behaves continuous looping but not getting exact result. What I did till now is:

constructor (public homeauth: Authservice, public navCtrl: NavController) {
  this.accesscheck();
}

accesscheck() {
  this.homeauth.accesscheck().then(response => {
    for (var i = 0; i < response.length; i++) {
      if (response[i]["c20"] !== true) {
        this.navCtrl.setRoot("TabsPage");
      }
    }
  });
}

I have response from my backend like this:

[
    {
        "c24": true,
        "statuscode": 65544
    },
    {
        "c23": true,
        "statuscode": 4259848
    },
    {
        "c22": true,
        "statuscode": 6357000
    },
    {
        "c21": true,
        "statuscode": 7405576
    },
    {
        "c20": true,
        "statuscode": 7929864
    },
    {
        "c19": true,
        "statuscode": 8192008
    },
    {
        "c18": true,
        "statuscode": 8323080
    }
]

my backend code something like this enter image description here

Upvotes: 0

Views: 97

Answers (3)

U rock
U rock

Reputation: 775

Its working something like this

findObjectByKey(array, key, value) {
  for (var i = 0; i < array.length; i++) {
      if (array[i][key] === value) {
          return array[i];
      }
  }
  return null;
}

   accesscheck() {
    this.homeauth.accesscheck().then(response => {
      this.obj = this.findObjectByKey(response, 'c77', true);
      if(this.obj){
        console.log("success")
      }else{
        this.navCtrl.setRoot("TabsPage");
      }
    });
  } 

i have passed this accesscheck() in constructor.

Upvotes: 0

Paul Isaris
Paul Isaris

Reputation: 483

I think that the problem is that you check response[i]["c20"] !== true in an object that might not even have a "c20" property. So you should first check if the response[i] object has that property.

Also, after you have navigated to the desired page, you should break; your for loop:

accesscheck() {
  this.homeauth.accesscheck().then(response => {
    for (var i = 0; i < response.length; i++) {
      if (response[i]["c20"] !== null) {
          if (response[i]["c20"] !== true) {
            this.navCtrl.setRoot("TabsPage");
            break;
          }
      }
    }
  });
}

Upvotes: 1

user7722867
user7722867

Reputation: 488

You are looping too many times. If you have more than one "false" statement in your data, you will end up navigating to the tabspage more than one time. You should either break out of the loop after you have encountered the first false, or you should set up a boolean value like "navigatedToTabsPage" which is initially set to false, but evaluates to true inside the if statement and thus terminates the loop (you would have to nest another if statement if so)

Upvotes: 0

Related Questions