SORU
10 NİSAN 2013, ÇARŞAMBA


Uygulama servis enjekte.config

App içine bir servis enjekte etmek istiyorum.yapılandırma, veri denetleyicisi denir önce alınabilir. Bu gibi çalıştım:

Servis:

app.service('dbService', function() {
    return {
        getData: function($q, $http) {
            var defer = $q.defer();
            $http.get('db.php/score/getData').success(function(data) {
                defer.resolve(data);            
            });
            return defer.promise;
        }
    };
});

Config:

app.config(function ($routeProvider, dbService) {
    $routeProvider
        .when('/',
        {
            templateUrl: "partials/editor.html",
            controller: "AppCtrl",
            resolve: {
                data: dbService.getData(),
            }
        })
});

Ama bu hata alıyorum:

Hata: Bilinmeyen sağlayıcı: EditorApp gelen dbService

Nasıl Kur doğru ve bu hizmeti enjekte etmek?

CEVAP
8 ŞUBAT 2014, CUMARTESİ


Özel AngularJS Sağlayıcı olarak hizmet sunuyor

Kabul cevabı ne diyor, aslında rağmenOLABİLİRne olduğunu niyetinde, ama ihtiyacın var bunu ayarlamak için bir sağlayıcı olarak yapılandırılabilir, böylece bu mevcut gibi bir hizmet sırasında yapılandırma aşama.. Önce değiştirmek Service bir sağlayıcı, aşağıda gösterildiği gibi. En önemli fark burada defer, değerini ayarladıktan sonra söz nesne $http.get tarafından döndürülen defer.promise özelliğini ayarladığınız

Hizmet Sağlayıcı:(sağlayıcı: hizmet tarifi)

app.provider('dbService', function dbServiceProvider() {

  //the provider recipe for services require you specify a $get function
  this.$get= ['dbhost',function dbServiceFactory(dbhost){

     return new DbService(dbhost);  //return the factory as a provider, that is available during the configuration phase
  }]

});

  function DbService(dbhost){
      var status;
      this.setUrl = function(url){
          dbhost = url;
      }


      this.getData = function($http){
            return $http.get(dbhost 'db.php/score/getData')
                    .success(function(data){
                        //handle any special stuff here, I would suggest the following:
                        status = 'ok';
                        status.data = data;
                     })
                     .error(function(message){
                        status = 'error';
                        status.message = message;

                     })
                     .then(function(){
                         return status;  // now we return an object with data or information about error for special handling inside your application configuration
                      })
      }
  }

Şimdi, yapılandırılabilir özel bir Sağlayıcı var, sadece enjekte etmen lazım. Önemli fark burada eksik olma "enjekte edilebilir Sağlayıcı".

config:

app.config(function ($routeProvider) { 


    $routeProvider
        .when('/',
        {
            templateUrl: "partials/editor.html",
            controller: "AppCtrl",
          resolve: {
              dbData: function(DbService, $http){
                 /*
                 *dbServiceProvider returns a dbService instance to your app whenever
                 * needed, and this instance is setup internally with a promise, 
                 * so you don't need to worry about $q and all that
                 */
                 return DbService('http://dbhost.com').getData();
              }
          }
        })
});

kullanım çözülmüş veri appCtrl

app.controller('appCtrl',function(dbData, DbService){
     $scope.dbData = dbData;

     //you can also create and use another instance of the dbService here...
     // to do whatever you programmed it to do, by adding functions inside the constructor
     // DbService(), the following assumes you added a rmUser(userObj) function in the factory
     $scope.removeDbUser = function(user){
         DbService.rmUser(user);
     }

})

Olası Alternatifleri

Aşağıdaki alternatif benzer bir yaklaşım olmakla birlikte, tanımı hizmet uygulaması bağlamında özel modül içinde .config, şifrelenmiş içinde yapılmasına izin verir. Sizin için doğru olan yöntemi seçin. Bakın aşağıda da tüm bu şeyler asmak yardımcı olmak için 3. bir alternatif ve yardımcı bağlantılar ile ilgili notlar için

app.config(function($routeProvider, $provide){
  $provide.service('dbService',function(){})//set up your service inside the module's config.

  $routeProvider
        .when('/',
        {
            templateUrl: "partials/editor.html",
            controller: "AppCtrl",
            resolve: {
                data: 
                }
            }
        })


});

Birkaç yararlı bir Kaynak

  • John Lindquist egghead.io, bu 5 dakika mükemmel bir açıklama ve bir gösteri var ve ücretsiz ders! Ben temelde $http belirli bu isteğin bağlamında yaparak onun gösteri değiştirilmiş
  • Providers AngularJS Geliştirici bakabilirsiniz
  • Ayrıca*/service/provider at clevertech.biz*19 hakkında mükemmel bir açıklaması var.

Sağlayıcı verir sana biraz daha fazla yapılandırma üzerinde .service yöntem, böylece daha iyi bir uygulama düzeyi sağlayıcı, ama olabilir de saklanması bunun içinde config nesnenin kendisi tarafından enjekte $provide içine config gibi

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Adam Outler

    Adam Outler

    19 EKİM 2006
  • spederson7

    spederson7

    17 Temmuz 2006
  • UCBerkeley

    UCBerkeley

    3 Mayıs 2006