0

In Angular Dependency Injector when ever we injecting a Type , we will includes them in providers array (May be in @NgModule decorator or @Component decorator. But in the following instance when we navigate programmatically we inject Router instance to constructor, But we don't provide in providers array as normally we do in Angular Dependency Injector.

What is the different here than Angular Dependency Injector ? for your reference I will attach both code

Programmatic Navigation - Code

import { Router } from '@angular/router';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  constructor(private router:Router) { }

  ngOnInit() {
  }

  onLoadServer(){
    this.router.navigate(['servers']);
  }

}

Angular Dependency Injector way - Code

import { Component,Input} from '@angular/core';
import { LoggingService } from '../logging.service';


@Component({
  selector: 'app-account',
  templateUrl: './account.component.html',
  styleUrls: ['./account.component.css'],
  providers:[LoggingService]
})

export class AccountComponent {
  @Input() account: {name: string, status: string};
  @Input() id: number;

  constructor(private logginService:LoggingService){

  }
  
  onSetTo(status: string) {
    
 
    this.logginService.loggingStatusChange(status);
    
  }
}

Aslam Jiffry
  • 1,306
  • 6
  • 23
  • 57

1 Answers1

1

RouterModule.forRoot already injects Router in root injector, thats why you don't have to include it in providers array any where. you can read about it here :-

https://angular.io/api/router/RouterModule#forroot

Aakash Garg
  • 10,649
  • 2
  • 7
  • 25
  • Yes, But we do that in imports array. not in providers array. is both same ? – Aslam Jiffry Aug 12 '21 at 13:08
  • 1
    if you import a module with providers in another module the services of that module becomes available automatically in your module. see source of router module here from line 121 :- https://github.com/angular/angular/blob/master/packages/router/src/router_module.ts – Aakash Garg Aug 12 '21 at 13:18