简体   繁体   中英

AngularJS - initialize ngResource object if API response is null

I am building an AngularJS app backed by a third-party API. I have a basic resource like this:

module.factory('UserPreference', function($resource) {
  return $resource('/users/:user_id/preferences/:preference_type_id', {
    user_id: "@user_id",
    preference_type_id: "@preference_type_id"
  })
})

If the user has not specified a preference for a certain preference type, the result will be null. I want to initialize the object in the case that the response is null.

{user_id: 1, preference_type_id: 1, preference: null}

I can see two options:

  1. Do this in transformResponse within the factory
  2. Handle it in the controller

1 seems like the cleaner option since this is really a data issue more than a controller issue, but I can't figure out the details of how to do that. Specifically, I can't access the :user_id and :preference_type_id params that get passed to the resource.

Should I just handle this in the controller? Is there something really obvious I'm missing?

Can yo do something like,

module.factory('UserPreference', function($resource, $location) {

if($location.search().preference_type_id){
  return $resource('/users/:user_id/preferences/:preference_type_id', {
    user_id: "@user_id",
    preference_type_id: "@preference_type_id"
  })
}

else{
       //do your initialization and return
      }


})

Wrap it on a function that you can call as many times as you like.

module.factory('UserPreference', function($resource, $q) {
  var resouce = $resource('/users/:user_id/preferences/:preference_type_id', {
    user_id: "@user_id",
    preference_type_id: "@preference_type_id"
  });  
  return function (userId, preferenceTypeId) {
    var promise = $q.defer();
    var defaultPreference = {user_id: 1, preference_type_id: 1, preference: null};
    $q.when(resouce.get({user_id: userId, preference_type: preferenceTypeId}))
    .then(function (userPreferences) {
      promise.resolve(userPreference || defaultPreference);
    }, function () {promise.reject('error')});

    return promise.promise;
  };
});

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