Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to share services across Modules in angular2

Tags:

angular

I am using an application structure as mentioned below

index.ts
|-app.module.ts
|-app.component.ts
|--hero (directory)
   |-hero.module.ts
   |-hero.ts (Data Object)
   |-hero.service.ts
   |-hero.component.ts
   |-index.ts (this file exports data obj, service, component & module)
|--dashboard (directory)
   |-dashboard.module.ts
   |-dashboard.component.ts
   |-index.ts (this file exports module and component)

I wish to use hero service in dashboard component. Below is the code snippet I am using right now and its working as expected. But not sure if its a good practice.

import { Component, OnInit } from '@angular/core';

import { Hero, HeroService } from '../hero/index';
import {Router} from '@angular/router';

@Component({
    moduleId: module.id,
    selector: 'my-dashboard',
    templateUrl: 'dashboard.component.html',
    styleUrls: ['dashboard.component.css']
})
export class DashboardComponent implements OnInit {
    heroes: Hero[] = [];

    constructor(private heroService: HeroService, private router: Router) { }

    ngOnInit(): void {
        this.heroService.getHeroes()
            .then(heroes => this.heroes = heroes.slice(1, 5));
    }

    gotoDetail(hero: Hero): void {
        let link = ['/detail', hero.id];
        this.router.navigate(link);
    }
}

I am curious to know if there is any way that I can access HeroService with reference to HeroModule rather than separately importing Hero object and HeroService from ../hero/index

like image 713
Mahesh Avatar asked Aug 25 '16 13:08

Mahesh


People also ask

Can I share services using modules?

Services provided in @NgModule() are shared with the whole application and therefore also with all modules in your application (except when the module where you provide the service is lazy loaded). If you've provided a service in an @NgModule, all non-lazy-loaded modules below may use that service.

How do I share a component between modules?

Sharing moduleslink You can put commonly used directives, pipes, and components into one module and then import just that module wherever you need it in other parts of your application. Notice the following: It imports the CommonModule because the module's component needs common directives.

What is especially useful when code is to be shared among multiple modules?

A shared library is especially useful when code is to be shared among multiple modules.

How do I pass data from one module to another in Angular 8?

You can import MemberCardModule into AppModule directly. Or import into ShareModule and import ShareModule into AppModule. It is important to import Modules into AppModule. And then you can you MemberCardModule.


2 Answers

from Range.io

So far our problem is that we are creating two instances of the same services in different levels of the DI tree. The instance created in the lower branch of the tree is shadowing the one defined at the root level. The solution? To avoid creating a second instance in a lower level of the DI tree for the lazy loaded module and only use the service instance registered at the root of the tree.

import { NgModule, ModuleWithProviders } from '@angular/core';
import { CounterService } from './counter.service';

@NgModule({})
export class SharedModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [CounterService]
    };
  }
}

With this setup, we can import this module in our root module AppModule calling the forRoot method to register the module and the service.

...
import { SharedModule } from './shared/shared.module';

@NgModule({
  imports: [
    SharedModule.forRoot(),
    ...
  ],
  ...
})
export class AppModule {}
like image 149
LeonardoX Avatar answered Nov 08 '22 17:11

LeonardoX


Services are shared across the entire application, so if you put it into a module, other component has acces to it. However, you still need to import the classes Hero and HeroService in component where you use them.

Imports at the top of a class and Modules has just a differents purpose.

like image 38
Alexis Le Gal Avatar answered Nov 08 '22 17:11

Alexis Le Gal