angularjs中provider,factory,service的區別和用法

angularjs中provider,factory,service的區別和用法

provider->factory->servicehtml

都能提供service,可是又有差異angularjs

service
第一次被注入時實例化,只實例化一次,整個應用的生命週期中是個單例模式,能夠用來在controller之間傳遞數據api

//使用new關鍵字實例化,因此直接使用this定義service
//不知道爲啥就看看js中的this怎麼玩的
.service('myService', ['', function() {
    this.getName = function() {
        return 'CooMark';
    }
}])

factoryapp

//返回一個對象,可能這是你喜歡的方式,使用call的方式實例化,其餘的和service同樣
//Internally this is a short hand for $provide.provider(name, {$get: $getFn}).
angular.module('app', [])
.factory('myFactory', ['', function() {
    return {
        getName: function() {
            return 'CooMark';
        },
        getTitle: function() {
            return 'Engineer'
        }
    }
}])

provider
這是惟一能注入到config的service,這樣定義的service在你開始注入以前就已經實例化,開發共享的模塊的時候經常使用它,可以在使用以前進行配置,好比你可能須要配置你的服務端的urlide

//兩種形式的參數,都是爲了獲得一個帶有$get屬性的對象
// Object: then it should have a $get method. The $get method will be invoked using $injector.invoke() when an instance needs to be created.
// Constructor: a new instance of the provider will be created using $injector.instantiate(), then treated as object.
angular.module('app', [])
.config(['$provider', function() {
    $provider.provider('myProvider', function() {
        this.$get = function() {
            return {
                getName: function() {
                    return 'CooMark';
                }
            }
        }
    });
    $provider.provider('myProvider', {
        $get: function() {
            return {
                getName: function() {
                    return 'CooMark';
                }
            }
        }
    });
}])

參考:
https://docs.angularjs.org/api/auto/service/$provide
http://www.cnblogs.com/joyco773/p/5702337.html
http://www.360doc.com/content/16/0728/14/22900036_579091190.shtml
https://my.oschina.net/tanweijie/blog/295067this

相關文章
相關標籤/搜索