简体   繁体   中英

How can i use array of objects from database as filter?

 // filter with data from database not working app.filter('position', function($http, dbOperations) { console.log(dbOperations.getAccessPosition()); var positions = []; //[{name:"cashier",id:1},{name:"operator",id:2}]; // get the object array from database with name and id dbOperations.views("getPositions", "").then(function(res) { positions = res; // this is the desired value: [{name:"cashier",id:1},{name:"operator",id:2}] }); var poitionName = ""; return function(positionNum) { positions.forEach(function(p) { if (p.id == positionNum) { poitionName = p.name; return false; } }); return poitionName; } }); app.service('dbOperations', function($http) { this.getAccessPosition = function() { return $http({ method: "POST", url: "/common/functions.php", data: { 'process': "getAccessPosition", 'data': "" } }).then(function success(res) { return res; }, function myError(response) { // console.log("Error"); }); } }); 

When I console.log the positions, it prints the data that I need. but the filter is not working. maybe because the data is from database and it is waiting to respond. dbOperations is the in the service and I use $http. Please help me with this. Thankyou.

In the service, just return the http request instead of unwrapping the promise.

app.service('dbOperations', function($http) {
  this.getAccessPosition = function() {
    return $http({
      method: "POST",
      url: "/common/functions.php",
      data: {
        'process': "getAccessPosition",
        'data': ""
      }
    })
  }
});

in the filter do the service call inside the callback function.

app.filter('position', function($http, dbOperations) {
  console.log(dbOperations.getAccessPosition());
  var positions = []; //[{name:"cashier",id:1},{name:"operator",id:2}];

  var poitionName = "";
  return function(positionNum) {
    dbOperations.views("getPositions", "").then(function(res) {
      positions = res.data;
      positions.forEach(function(p) {
       if (p.id == positionNum) {
        poitionName = p.name;
        return false;
       }
      });
      return poitionName;
    });    
  }
});

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