Angular 6 Sharing Service… or not…

Different ways to share Service instance in Angular 6.

Service instance shared across entire application.

  • Declare `providedIn: ‘root’` property of `@Injectable` decorator in the Service. Then inject service to component’s constructor as usual.
  • import { Injectable } from '@angular/core';
    
    @Injectable({
      providedIn: 'root'
    })
    export class Service1Service {
      constructor() {
      }
    }
    
  • Declare service in `providers` property of `@NgModule` decorator in highest module (Ie: app.module.ts). Then inject service to component’s constructor as usual.
  • app.module.ts

    @NgModule({
        declarations: [...],
        imports: [...]
        providers: [Service1Service]
    })
    

Service instance shared across module.
Declare service in `providers` property of `@NgModule` decorator in any module except the highest module (Ie: user.module.ts, order.module.ts, etc). Then inject service to component’s constructor as usual.

user.module.ts

@NgModule({
    declarations: [...],
    imports: [...]
    providers: [Service1Service]
})

Service instance in every single component (not shared).
Declare service in `providers` property of `@Component` decorator in any component. Then inject service to component’s constructor as usual.

component1.component.ts

import { Component } from '@angular/core';
import { Service1Service } from '../service1.service';

@Component({
  selector: 'app-component1',
  templateUrl: './component1.component.html',
  styleUrls: ['./component1.component.css'],
  providers: [Service1Service]
})
export class Component1Component {
  constructor(private service1: Service1Service) {
  }
}
Advertisements

Angular – All Possible Solutions for ‘No NgModule’

The error “No NgModule metadata found for ‘AppModule'” could be caused by various reason:

  1. Moving Angular project folder.
  2. Upgrading dependencies.
  3. Upgrading Angular version.

Here are summary of all possible answers I have found during my battle. All answers are from Github and Stackoverflow.

  1. You are trying to bootstrap App, which is not a real module. Instead, bootstrap Module. Source.
  2. A simple edit in the app.module.ts file (like delete a bracket and put it back) did the trick. Source.
  3. This one work for me. Try to remove node_modules and package-lock.json then run npm install. Source.
  4. Arrange include list in tsconfig.json so that the app.module.ts was located first. Source.
  5. Remove webpack, install latest angular/cli, delete node_module, clear cache, reinstall angular/cli, then run npm install. Source.
  6. Upgrading angular/cli. Source.
  7. App.module.ts has extra comma. Source.
  8. Change import path in App.module.ts. Source.