简体   繁体   English

Angular 2:@component装饰器中的指令和提供程序

[英]Angular 2 : Directives and providers in @component decorator

Hi i am new to Angular 2, i referred many other similar post but nothing helped me. 嗨,我是Angular 2的新手,我曾推荐过许多其他类似的文章,但没有任何帮助。

Below are my Queries 以下是我的查询

  1. When to use Directives and providers parameters in @component decorator? 何时在@component装饰器中使用指令和提供程序参数? Do i need to pass component inside any of this parameters while i import component 导入组件时是否需要在任何此参数内传递组件

  2. I made a http subscribe call inside oninit() but it never's gets called when page loads I get undefined value in console. 我在oninit()内进行了http订阅调用,但是当页面加载时,在控制台中未定义的值从未调用过。 how do i call it when a page loads. 当页面加载时,我怎么称呼它。

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

  1. how do i communicate between 2 components while routing? 路由时如何在2个组件之间进行通信?
  2. What is the difference between Directive and Component 指令和组件有什么区别

-- When to use Directives and providers parameters in @component decorator? -何时在@component装饰器中使用指令和提供程序参数?

Directives , when you want to use directives , you can load those inside that , but that was in older version. 指令,当您要使用指令时,可以将其加载到指令中,但是该指令是较旧的版本。

Providers , when you want to load services in your components or modules 提供商,当您想在组件或模块中加载服务时

-- First of all change your code to this : -首先将您的代码更改为此:

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

  }

This is async call , so you will not get data in sequence , your console log will not called after http call finishes , it will be called as soon as the api called, so you have to log that inside subscribe method. 这是一个异步调用,因此您不会按顺序获取数据,http调用完成后将不会调用您的控制台日志,它会在api被调用后立即被调用,因此您必须将其记录在subscribe方法中。

-- how do i communicate between 2 components while routing? -路由时如何在2个组件之间进行通信?

By using CommonService and provide it at route level or as per the project structure and your requirements. 通过使用CommonService并在路线级别或根据项目结构和您的要求提供它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM