简体   繁体   中英

Angular Js how to refresh a new factory instance

I am using a factory to get list of folders and display it in the front end. Also in the front end i have form where i can add new folder to the existing list. After adding a folder i want to refresh my factory instance and display the updated folder list.

// factory

angular.module('myapp').factory('archiveService', ['$http', 'ApiUrl', function($http, ApiUrl) {
var archiveService = function() {
    this.repos = [];
    this.busy = false;
    this.page = 0;
};
archiveService.prototype.nextPage = function() {
    if (this.busy) return;
    this.busy = true;
    var url = ApiUrl.url + '/folders/?page=' + this.page;
    $http.get(url).then(function(res) {
        console.log(res);
        this.repos = res.data;
        if (items.repos == 0) {
            return;
        }
        this.page += 1
        this.busy = false;
    }.bind(this)).catch(function(data) {
    }.bind(this));
};
return {
    archiveService: archiveService,
}

}]);

// this is my controller

angular.module('myapp').controller('archiveModalController', ['$rootScope', '$scope','archiveService', function($rootScope, $scope, archiveService) {

// I want to refresh this and show new data on update

    $scope.archivelist = new archiveService.archiveService();

}])

I would like to know how can i refresh so i can get the new updated data

$scope.archivelist = new archiveService.archiveService();

Angular services follow the singleton pattern meaning the instantiation of a class is restricted to a single object.

Also, since you are using a factory:

angular.module('myapp').factory('archiveService', [<dependencies>, function () {
    function nextPage() {
        //code here
    );

    return {
        nextPage: nextPage
    }

}]);

Then in your controller you simply:

archiveService.nextPage();

Seeing the variables in place I believe nextPage could simply receive the page as a parameter and since repos is an array I guess you meant to add the new fetched data to that array? Which would be: this.repos.push(res.data;) instead of this.repos = res.data ;

Point is, each time you want to request new data you should call the correct service/factory method from the controller.

So at your controller init, you only need:

(function init() {
    $scope.archivelist = archiveService.nextPage();
})();

Although like I stated, you should probably have an initial value like nextPage(1) and from there send the desired page you want to the factory method to be handled correctly.

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