【问题标题】:Resolving bindings with a controller class使用控制器类解析绑定
【发布时间】:2017-09-08 11:47:37
【问题描述】:

我有一个带有控制器类的组件,它使用绑定对象作为输入参数。构造函数运行后,我可以访问控制器中的参数。但我不能将它作为构造函数参数传递。

制作plunker 我找到了一个使用 $onInit 方法的可行解决方案。 (ui-router doc)

但这是正确的方法吗?希望这对某人有所帮助,请告诉我是否可以改进。

这是控制器:

class Controller {
  constructor(){
    'ngInject';
    this.$onInit = function(){      // Comment this
       this.problemScopeHere = angular.copy(this.param);  
    }                               // Comment this
    console.log(this.param);            
  }
  get(){
    this.problemScopeHere = this.param;
  }
}

这里是组件

 let Component = {
   bindings : {
      param : "="
   },
   controller : Controller,
   controllerAs: '$ctrl',
   templateUrl: 'component.html'
};

let app = angular.module('app', ['ui.router']);
app.component('comp', Component);

【问题讨论】:

    标签: angularjs angular-ui-router


    【解决方案1】:

    您应该将 param 作为属性添加到您的控制器类中。

    【讨论】:

      【解决方案2】:

      我认为你应该使用resolve,因为你在 UI Router 上的版本可以使用routing to component

      .state('app.home' ,{
            url: '/home',
            component: 'comp',
            bindigns: {
              param: 'param',
            },
            resolve: {
              param: function () {
                return {
                  string: 'I am the object param'
                }
              }
            }
          });
      

      工作小提琴(与你的有点不同,因为我不知道 home.html 是否真的需要,我认为这只是为了演示目的):https://plnkr.co/edit/jaXQN7YmmkI8AC1DxohI?p=preview。而且,你不能在第一次 $onChanges 之前使用绑定(第一次运行是在 $onInit 之前),或者 $onInit 从 Angular 1.6 运行,所以建议不要在 contructor 中依赖它们 - 你可以在$onInit 中依赖它们,我认为resolve 是最现代的方法——我曾经在template 中像你一样传递参数,但从UI Router 1.x 开始更容易。您可以将$onInit 声明为常规类方法。而且,您不必使用controllerAs: $ctrl。如果您不提供$ctrl,则将其用作默认值 - 我鼓励您始终使用默认值,以确保所有组件的一致性。

      【讨论】:

        猜你喜欢
        • 2018-01-22
        • 1970-01-01
        • 1970-01-01
        • 2020-06-24
        • 1970-01-01
        • 2019-09-22
        • 1970-01-01
        • 2017-01-10
        • 2021-08-14
        相关资源
        最近更新 更多