1

After a day of search found nothing what i am looking for !

i have some methods (also can say services) which i have written in the separate file then i have to use those methods throughout the whole angular2 app. i know if we import that file at the time of bootstrap we able to use those methods in the whole app. but my question is what if i have to more than two global files. should i have to import all files in the constructor of every component (in which components service required)? or is there any other alternate ?

for example i have file named GlobalService.ts.

export clas xyz{
 constructor(private base_path_service: GlobalService){
   //stuff...
    }
}

Q1:- Is there any alternate to avoid initializing of GlobalService every time in the constructor ?

Q2:- whats the benifit of use @injectable and @inject while service injection ?

Q3:-

export clas xyz{
 constructor(private base_path_service: GlobalService){
   //stuff...
    }
}

or

class xyz{
  constructor(@Inject(GlobalService) GlobalService: globalService) {
      //stuff....
  }
}

which one is best and why ?

SnareChops
  • 13,175
  • 9
  • 69
  • 91
Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215

1 Answers1

0

Q1: There is no sane alternative.

Q2: @Injectable() has to be added to services that have constructor arguments otherwise Angulars DI can't create instances.

@Inject(GlobalService) is redundant. There are special features where @Inject() is helpful like shown here https://stackoverflow.com/a/35217704/217408

Q3: the first example. See Q2.

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • but i don't want to put my global service into the constructor of component where that service is to be used then what ? – Pardeep Jain Feb 06 '16 at 13:17
  • I might have misunderstood the "import" in "import all files in the constructor of every component". What you could do is to create one service (`globalService`) like you mentioned, that provides access to all other services. This way you only have to inject this one service in the constructor (still everywhere) and call functions like `this.globalService.specialService.doSomething()`. There is no feasible other way to get global instances than through the constructor. What's the problem with this? – Günter Zöchbauer Feb 06 '16 at 13:23