-1

I am learning Angular DI, But The Provided Example (https://angular.io/guide/providers#providedin-and-ngmodules) Is Not Working Can Anyone Help me In Understanding Here Is The Link Of The Stackblitz I Am Working On. https://stackblitz.com/edit/angular-ivy-k1gvth Thanks, Keshav

3 Answers3

0

You need to add AppService to your providers array in app.module.ts as specified in the docs.

Berk Kurkcuoglu
  • 1,453
  • 1
  • 9
  • 11
  • But I want to achieve it using only providedIn strategy. If I inject service in module then I even don't need to write @Injectable() in service. – Keshav Sharma Jun 17 '20 at 12:38
  • You need to use Injectable annotation any ways to be compatible with Angular DI. If you just want to providedIn without adding it to providers you need to use it as providedIn: 'root' as mentioned by @Shabbir Dhangot – Berk Kurkcuoglu Jun 17 '20 at 12:42
  • Thanks for clarifying my doubt. – Keshav Sharma Jun 17 '20 at 13:14
0

You can use provideIn value as root. With that no need to provide in app module.

 providedIn: 'root'

If you want to add this in app.module.ts then remove Injectable decorator from service and add in providers list of app.module.ts.

You can read official documentation for more details. https://angular.io/guide/singleton-services

Also You can't give module name in providedin. There are predefined options for that 'root', 'any' and 'platform'. You can read more at https://angular.io/api/core/Injectable

Shabbir Dhangot
  • 8,954
  • 10
  • 58
  • 80
0

You need to add providers in the app.component.ts file. I have added the snippet below and it working fine.

import { Component, VERSION } from '@angular/core';
import { AppServiceService } from './app-service.service';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  providers: [AppServiceService]
})
export class AppComponent  {
  name = 'Angular ' + VERSION.major;
  constructor(ser: AppServiceService) {
      this.name = ser.sayHello();
  }
}
David Buck
  • 3,752
  • 35
  • 31
  • 35
SKV
  • 1
  • 1
  • Yes this is also one of the way document suggested. But I want to achieve it only using providedIn property of @Injectable. BTW Thanks for commenting. :) – Keshav Sharma Jun 17 '20 at 13:15