简体   繁体   English

providedIn 属性在 Angular 服务不工作

[英]providedIn Property In Angular Service Is not working

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.我正在学习 Angular DI,但提供的示例( https://angular.io/guide/providers#providedin-and-ngmodules )不起作用任何人都可以帮助我理解这是我正在处理的 Stackblitz 的链接。 https://stackblitz.com/edit/angular-ivy-k1gvth Thanks, Keshav https://stackblitz.com/edit/angular-ivy-k1gvth谢谢,Keshav

You need to add AppService to your providers array in app.module.ts as specified in the docs.您需要按照文档中的规定将 AppService 添加到 app.module.ts 中的 providers 数组中。

You can use provideIn value as root .您可以将 provideIn 值用作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.如果你想在app.module.ts中添加它,那么从服务中删除 Injectable 装饰器并添加 app.module.ts 的提供者列表。

You can read official documentation for more details.您可以阅读官方文档了解更多详细信息。 https://angular.io/guide/singleton-services 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'. “root”、“any”和“platform”有预定义的选项。 You can read more at https://angular.io/api/core/Injectable您可以在https://angular.io/api/core/Injectable阅读更多信息

You need to add providers in the app.component.ts file.您需要在app.component.ts文件中添加提供程序。 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();
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM