1

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

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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"
@user3844198 if this helps you, you can mark as correct and help others to find it easily
0

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 ?

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.