简体   繁体   中英

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.

Below are my Queries

  1. When to use Directives and providers parameters in @component decorator? 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. 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. What is the difference between Directive and Component

-- When to use Directives and providers parameters in @component decorator?

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.

-- how do i communicate between 2 components while routing?

By using CommonService and provide it at route level or as per the project structure and your requirements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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