-1

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

4

3 回答 3

0

您需要在app.component.ts文件中添加提供程序。我在下面添加了代码片段,它工作正常。

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();
  }
}
于 2020-06-17T13:03:13.880 回答
0

您需要按照文档中的规定将 AppService 添加到 app.module.ts 中的 providers 数组中。

于 2020-06-17T12:17:55.203 回答
0

您可以将 provideIn 值用作root. 无需在应用程序模块中提供。

 providedIn: 'root'

如果要添加它,请app.module.ts从服务中删除 Injectable 装饰器并添加 app.module.ts 的提供者列表。

您可以阅读官方文档了解更多详细信息。https://angular.io/guide/singleton-services

此外,您不能在提供的模块名称中给出模块名称。“root”、“any”和“platform”有预定义的选项。您可以在https://angular.io/api/core/Injectable阅读更多内容

于 2020-06-17T12:18:04.727 回答