【问题标题】:injecting ui-router resolve to directive将ui-router解析注入指令
【发布时间】:2014-12-08 20:18:35
【问题描述】:

我正在使用 ui-router,我正在解析一些数据,我想将解析注入到我的自定义指令中,下面是我正在做的代码

 module portal {
           $stateProvider.state('portal', {
        url: '/demo',
        template: tpl.html,
        abstract: true,
        resolve: {

            demoResolve:function(){
                 return 'foo';//here i am returing a promise
        }
    });    

}


module portal.directives{


export class demoDirevtive{

    static $inject =['demoResolve'];
    constructor(demoResolve){
        console.log(demoResolve)
        var directive: ng.IDirective = {};
        directive.link = (scope, element, attrs, ctrl) => {

        };
        directive.restrict = "EAC";

        return directive;
    }
  }
}

但我收到未知提供商的错误

【问题讨论】:

    标签: angularjs typescript angular-ui-router


    【解决方案1】:

    从阅读他们的代码来看,这似乎是不可能的,他们有一个局部变量,他们将其注入到您在视图上定义的控制器中,也无法通过 $inject 服务访问它。

    最简单的解决方案是将它放在控制器的范围内,然后在指令中使用它。

    您还可以创建一个真正的服务,它将保存您应用程序中的所有已解析对象,即:

    resolve: {
         demoResolve: ['myResolvingService', function(resolver) {
              resolver.myValue = 'Foo';
              return 'Foo';
         }]
    

    我知道这不是您要找的东西,但它只是看起来不受支持。

    【讨论】:

    • 似乎 Angular 与 ui-router 解析不能很好地配合,我的意思是我不认为我们可以很好地注入我发现存储在 rootscope 中的解决方法并在指令中访问 rootscope
    • 是的,这是另一种解决方案,存储在 rootscope 上是最简单的解决方案,但我尽量避免它,因为它很容易变得混乱,就像在窗口上保存东西一样。
    • 按照设计,ui-router 解析只能注入到控制器和 onEnter/onExit 回调中。它们不能通过 $injector 全局注入。
    • @PranayDutta 我会把它放在控制器的 $scope 上,而不是 $rootScope 上。
    【解决方案2】:

    这里是如何通过控制器将解析值传递给指令的示例:

            .state('something.edit', {
                url: '/:id',
                template: '<something-edit title="title"></something-edit>',
                controller: function($scope, $title){
                    $scope.title = $title;
                },
                resolve: {
                    $title: ()=>{
                        return 'Something Edit';
                    }
                }
            });
    

    【讨论】:

    • 嗨汤姆,你能在这里提供更多信息吗?在您的示例中,我看不到您如何将 resolve $title 注入指令。
    • 通过模板中的属性 title="title" 注入。
    • 这种方法有点麻烦,但我在切换到“类似组件的路由”时最终还是这样做了。无论如何希望有人能想出更好的方法,这样我们就可以放弃代理控制器。
    【解决方案3】:

    他们在 2016 年增加了对此的支持。

    这是github线程:

    https://github.com/angular-ui/ui-router/issues/2664#issuecomment-204593098

    重要的部分是:

    在 0.2.19 中,我们将 $resolve 添加到 $scope,允许您执行“路由到组件模板”样式

    模板:&lt;my-directive input="$resolve.simpleObj"&gt;&lt;/my-directive&gt;,

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-12
      • 1970-01-01
      • 1970-01-01
      • 2015-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多