1

I know if i have a exported service,

import { Injectable } from '@angular/core';
@Injectable()
export class StudentService {
}

I can import this service into my component:

import { StudentService } from "./student-.service";

But, if my service is not a exported class, how do I import this unexported service into angular 2 component?

(function() {
    "use strict"

    class StudentService {

    }  
    angular.module('test').service('StudentService');
})();

My component and service are not within the same folder/module.

My component is inside: AFolder/Student/student.component.ts

My service is inside: BFolder/Shared/student.service.js

AFolder and BFolder both are under MainFolder.

MainFolder

-AFolder

-BFolder

I cannot find the solution for my question both from Google and StackOverflow. Please advise. Thanks.

FullStackDeveloper
  • 910
  • 1
  • 16
  • 40

1 Answers1

1

The reason why code is wrapped with IIFE like in the original post is that all variables and declarations stay local and don't leak to global scope. As a result, local variables cannot be retrieved from outside IIFE even when this is necessary.

AngularJS services are stored inside injector and can't be retrieved from the outside before application boostrap.

The only proper way to get StudentService class from the outside is to export it. If this is module scope, IIFE is unneeded and undesirable here:

export class StudentService {...}  
angular.module('test').service('StudentService', StudentService );
Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • I have other components (angularjs 1.5) are using this unexported service, and I have not converted those angularjs 1.5 components into angular 2 components. If I just make this StudentService as a exported class, will this affect those angualarjs 1.5 component use this new exported StudentService? – FullStackDeveloper Jul 24 '17 at 21:38
  • It depends on how A1 application is being built. If `export` word won't cause syntax error, there will be no other consequences for A1 app. – Estus Flask Jul 24 '17 at 21:39
  • Thanks. I am trying it. – FullStackDeveloper Jul 24 '17 at 21:41
  • While export won't hurt in A1 app, it cannot be guaranteed that `@Injectable()` won't. It's probably isn't needed there at all. See https://stackoverflow.com/a/39029435/3731501 on how `Injectable` works. It depends on what StudentService is really is. If it has dependencies that should be injected by DI in A2 app, it likely should be annotated there and not in file that is used in A1. – Estus Flask Jul 24 '17 at 21:56