Is there a way to return "stories" by setting "vm.stories = storyDataAsFactory.stories" instead of the current method "vm.stories = storyDataAsFactory.stories()" ? I've tried various combinations without any luck. Additionally, it seems that I can call storyDataAsFactory.getStories without using parentheses, which aligns with how it's set up. However, when I create a function to return self.stories, it doesn't seem to work.
The following code is functioning correctly -
storyDataAsFactory.$inject = ['$http', '$q'];
angular.module('ccsApp').factory('storyDataAsFactory', storyDataAsFactory);
function storyDataAsFactory($http, $q) {
var self = this;
var stories = [];
function getStories(url) {
url = url || '';
var deferred = $q.defer();
$http({method: 'GET', url: url})
.success(function (data, status, headers, config) {
self.stories = data;
deferred.resolve(data);
})
.error(function (data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
}
function listStories() {
return self.stories;
}
return {
stories: listStories,
getStories: getStories('stories.json')
};
}
UPDATE:
I'm still facing issues. Here's my updated code based on community suggestions -
storyDataAsFactory.$inject = ['$http', '$q'];
angular.module('ccsApp').factory('storyDataAsFactory', storyDataAsFactory);
function storyDataAsFactory($http, $q) {
var stories = [];
function getStories(url) {
url = url || '';
if (url !== '') {
var deferred = $q.defer();
//check if ajax call has already been made;
//if so, data exists in cache as local variable
if (stories.length !== 0) {
deferred.resolve();
return deferred.promise;
}
$http({method:'GET', url:url})
.success(function (data, status, headers, config) {
stories = data;
deferred.resolve();
})
.error(function (data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
} else {
alert('URL was empty.');
}
}
return {
stories: stories,
getStories: function(url) {
getStories(url);
}
};
}
storyDataAsFactory.stories does not provide any output. Please note that I have confirmed that resolve was executed properly, ruling out asynchronous issues. This problem has been consuming my time for hours without any breakthrough.