【问题标题】:How to Access the Component Inside of Annotation in Angular2?如何在Angular2中访问注释内部的组件?
【发布时间】:2016-03-31 19:03:49
【问题描述】:

这只是我试图了解生命周期并尝试在加载组件之前执行一些逻辑,因此我找到了CanActivate Annotation。

我在组件中有一个要调用的函数,因此我需要该组件;我已经注入了它......它似乎过于复杂。

// HomeComponent Component
@Component({
  selector: 'HomeComponent',
  template: '<h2>HomeComponent Us</h2>'
})
@CanActivate((next,prev) => {

  let injector: any = Injector.resolveAndCreate([HomeComponent]);
  let theComponent: HomeComponent = injector.get(HomeComponent);

  return theComponent.canActivate(next,prev)
})

class HomeComponent {
  data = {}
  myresolver: any

  constructor() {
    console.log("in constructor", this.data)
  }

  setData(data: any) {
    this.data = data
  }

  canActivate(nextInstr, currInstr) {
      console.log("in my resolver");
      var that = this;
      return new Promise(function(resolve, reject) {
        setTimeout(function() {
          var data = { data: "Aaron" };
          that.setData(data)
          resolve(data);
        }, 2000)
      });
    }

}

【问题讨论】:

标签: javascript typescript angular angular-routing


【解决方案1】:

事实上你不能,因为注释中的处理是在实例化(或不实例化)组件之前调用的。

我猜你想将 Angular1 路由器的解析功能用于 Angular2。实际上,尚不支持此类功能。有关更多详细信息,您可以在 Angular github 中查看此问题:

以下两个链接为您的用例提供了一些解决方法:

希望对你有帮助, 蒂埃里

【讨论】:

  • 我想我希望将访问控制器的逻辑保留在控制器中,但我想这不是正确的模式......我确实看到了注入包含登录的服务的方法canActivate 方法,但正在寻找不同的东西......谢谢
  • 是的,可以从 CanActivate 函数引用服务,但不能附加组件的引用。仅供参考,Angular2 中不再有控制器的概念 ;-)
猜你喜欢
  • 2017-01-28
  • 2017-06-05
  • 1970-01-01
  • 2021-02-15
  • 1970-01-01
  • 2016-05-11
  • 2017-11-29
  • 2015-10-23
  • 2016-03-31
相关资源
最近更新 更多