Imagine that we have 3 components and one of them has some function which I want to use in other components. All these components are on the same level (siblings).

file1.ts
export class ComponentWithFunction() {
    function getData() {
        console.log('data has been fetched');
    }
}

file2.ts
export class ComponentA() {
    // here I want to have possibility to use getData
}

file3.ts
export class ComponentB() {
    // here I want to have possibility to use getData
}

What should I do to have an access to getData function from other component? I know that I can create SharedService and Inject it into specified components but is there any other way like using static functions or something like that ?

Thank you

share|improve this question

Why Component ? Angular 2 says, that you must to use services for retrieving data and refactoring data access to a separate service keeps the component lean and focused on supporting the view. It also makes it easier to unit test the component with a mock service.

You can put it into the service and inject that service in each Component in which you want to use that function.

Add that service into the app module's providers and inject in the constructors like

file1.ts

@Injectable()
export class ComponentWithFunction() {
    function getData() {
        console.log('data has been fetched');
    }
}

file2.ts
export class ComponentA() {
    constructor(private service: ComponentWithFunction)
}

file3.ts
export class ComponentB() {
    constructor(private service: ComponentWithFunction)
}

For more see Service in Angular 2.

share|improve this answer
    
As a rule of thumb, always use services to retrieve data See: angular.io/docs/ts/latest/tutorial/toh-pt4.html "We create a reusable service to manage our hero data calls" – hkievet Feb 9 at 18:39

So, maybe different example.

Let's say that I have Component responsible for Modal Element on page. Context of such component has a logic, methods like open, close, refresh and so on.

As I understand well, to use open() or close() method from different component, I have to create Modal as a service and Inject it into all places where I want to use it right? No option to subscribe the event / method from Modal ?

share|improve this answer
    
See here. You need to add your modal component into another one yes? So you can give to your modal component a template variable like <modal #myModal></modal and get that element in your component with @ViewChild('myModal') modal. And all public functions on that modal component will be accessible in your component via modal – Suren Srapyan Feb 9 at 18:58

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.