简体   繁体   English

Angular承诺多次

[英]Angular promise multiple times

I'm trying to replicate a couchDB like system. 我正在尝试复制像couchDB这样的系统。 My backend is Parse server and my frontend is Ionic (1) 我的后端是Parse服务器,我的前端是Ionic(1)

What i'm trying to achieve is to fasten my application with localstorage. 我想要实现的是用localstorage来固定我的应用程序。

Currently: GetUserAds 目前:GetUserAds

-> Has localstorage? - >有localstorage吗?

--> Yes - >是的

---> Return localstorage --->返回localstorage

--> No - >不

---> Get database call --->获取数据库调用

----> Return and put local ---->返回并放置本地

But what i really would like is the local return to fetch the database in background and return that data as well if it's changed 但我真正想要的是本地返回在后台获取数据库并返回该数据,如果它已更改

This is because my application has many users and changes a lot. 这是因为我的应用程序有很多用户并且变化很大。

Could i do something like this. 我可以这样做吗?

getUserAds(user).then(function(data) {
//Local data
}).then(function(dataDB) {
//Database updated data
})

You could use the notify callback provided on angular promises: 您可以使用角度承诺提供的notify回调:

function UserService($timeout, $q) {
    var users = ["user1", "user2"]; //localStorage.getItem('users');
    function get() {
    var deferred = $q.defer();
    //call your backend here $http.get('....')
    $timeout(function() {
      //if(remoteUsers !== users) {
                deferred.resolve({local: false, users: users.concat('user3')});
      //}

    }, 3000);
    $timeout(function() {
    if(users) {
        deferred.notify({local: true, users: users});
    }

    }, 100)

    return deferred.promise;
  }

    return {
    get: get
  };
}

and in your controller 并在你的控制器

function MyCtrl($scope, $users) {
    $scope.name = 'Superhero';
    $scope.myUsers = [];

    $users.get()
        .then(setUsers, null, setUsers);

     function setUsers(users) {
        $scope.myUsers = users;
      }
}

Here you can see a little jsfiddle: http://jsfiddle.net/Lvc0u55v/1596/ 在这里你可以看到一个小小的jsfiddle: http//jsfiddle.net/Lvc0u55v/1596/

You can do that if you use this service from the Angular API: Angular Promises . 如果您使用Angular API中的此服务,您可以这样做: Angular Promises

This is how I would do it: 我就是这样做的:

getUserAds(user).then(function(response) {
    // useMyData
});

function getUserAds {
    if( thereIsLocalData ) {
        return getLocalData(); // this returns a $q promise
    } else {
        return getDataDB() // Here I'm returning an $http Promise
    }
}

function getDataDB (params)  {
    return $http.get(host, params, {}); // I'm returning the $http Promise!
}

function getLocalData (params) {
    return $q(function(resolve, reject) {
        resolve(myLocalData);
  }); // return the $q promise!
}

This way you are using local communications the same way as Online communications and you can simplify your logic. 这样,您可以像在线通信一样使用本地通信,并且可以简化逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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