【问题标题】:Angular 2 : Directives and providers in @component decoratorAngular 2:@component 装饰器中的指令和提供程序
【发布时间】:2017-08-24 04:11:03
【问题描述】:

您好,我是 Angular 2 的新手,我参考了许多其他类似的帖子,但没有任何帮助。

以下是我的查询

  1. 何时在@component 装饰器中使用指令和提供者参数?导入组件时是否需要在任何此参数中传递组件

  2. 我在 oninit() 中进行了 http 订阅调用,但在页面加载时它从未被调用我在控制台中得到未定义的值。页面加载时如何调用它。

ngOnInit() {
    this.loginService.getLoginData()
      .subscribe(data => {
        this.loginData = data;
        this.loginDataLength = data.length;
      });
      console.log(this.loginData);
  }
  1. 路由时如何在 2 个组件之间进行通信?
  2. 指令和组件有什么区别

【问题讨论】:

  • console.log() 调用在 this.loginData = data; 之前执行,因为 getLoginData() 是异步的。
  • @jay,如果这回答了你的问题,请你接受答案吗?

标签: angular


【解决方案1】:

-- 何时在@component 装饰器中使用 Directives 和 providers 参数?

指令,当你想使用指令时,你可以在里面加载那些,但那是旧版本的。

Providers ,当你想在你的组件或模块中加载服务时

-- 首先将您的代码更改为:

ngOnInit() {
    this.loginService.getLoginData()
      .subscribe(data => {
        this.loginData = data;
        this.loginDataLength = data.length;
        console.log(this.loginData);
      });
      
  }

这是异步调用,所以你不会按顺序获取数据,你的控制台日志不会在http调用完成后调用,它会在api调用时调用,所以你必须在订阅方法中记录。

-- 路由时如何在 2 个组件之间进行通信?

通过使用 CommonService 并在路由级别或根据项目结构和您的要求提供它。

【讨论】:

  • 只是添加,使用构造函数而不是onInit。因为,有时它会异步工作。
  • Angular 2 本身建议尽可能使用 ngOnInit 代替构造函数。
  • 当我在另一个组件中导入组件时,我是否需要在任何此指令和提供程序参数中传递组件
  • 不,你需要在模块端做,但服务是依赖的。你可以在模块和组件两边使用服务。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-19
  • 2016-10-31
  • 1970-01-01
  • 2017-01-21
  • 2016-04-13
  • 1970-01-01
相关资源
最近更新 更多