在 app.config 中注入服务 [英] Inject service in app.config

查看:24
本文介绍了在 app.config 中注入服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 app.config 中注入一个服务,以便可以在调用控制器之前检索数据.我是这样试的:

I want to inject a service into app.config, so that data can be retrieved before the controller is called. I tried it like this:

服务:

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;
        }
    };
});

配置:

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

但我收到此错误:

错误:未知提供者:来自 EditorApp 的 dbService

Error: Unknown provider: dbService from EditorApp

如何更正设置并注入此服务?

How to correct setup and inject this service?

推荐答案

Alex 提供了无法完成您想做的事情的正确原因,因此 +1.但是您遇到这个问题是因为您还没有完全使用解决方案的设计方式.

Alex provided the correct reason for not being able to do what you're trying to do, so +1. But you are encountering this issue because you're not quite using resolves how they're designed.

resolve 接受服务的字符串或返回要注入的值的函数.既然你在做后者,你需要传入一个实际的函数:

resolve takes either the string of a service or a function returning a value to be injected. Since you're doing the latter, you need to pass in an actual function:

resolve: {
  data: function (dbService) {
    return dbService.getData();
  }
}

当框架去解析data时,它会将dbService注入到函数中,这样你就可以自由地使用它了.您根本不需要注入 config 块即可完成此操作.

When the framework goes to resolve data, it will inject the dbService into the function so you can freely use it. You don't need to inject into the config block at all to accomplish this.

祝您好胃口!

这篇关于在 app.config 中注入服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆