【问题标题】:why angular2 service is getting called multiple time?为什么 angular2 服务被多次调用?
【发布时间】:2016-10-21 21:39:26
【问题描述】:

我有一项服务 (MyService),我包含在我的项目模块中。 我正在我的每个组件中创建一个 MyService 类型的私有变量来设置和获取该服务中的数据。

在我的控制台日志中,我看到同一个服务被多次调用。

@NgModule({
  imports: [
    BrowserModule,
    routing,
  ],
  declarations: [
    AppComponent
  ],
  providers: [
    MyService,
  ],
  bootstrap: [AppComponent]
})


//Here is my Component code which create a private variable in my component

@Component({
  selector: 'summary',
  templateUrl: 'summary.component.html'
})
export class SummaryComponent extends OnInit {

  constructor(
              private myService: MyService,
              ) {
    super();
  }

如何多次停止对象创建?

【问题讨论】:

  • 调用服务的代码在哪里?什么方法被多次调用?您的页面上有多少个摘要组件?
  • 我在这里只给出了一个组件,这样的组件还有很多。在我的每个组件的应用程序中,MyService 类型变量被创建并注入到代码中给出的构造函数中。
  • 这不能回答我的问题

标签: angular angular2-services


【解决方案1】:

您应该使用共享模块来激活服务,这样一次只有一个服务实例。

请参阅我在Can't load shared directives of a NgModule in other NgModules 的回答,了解如何实现共享模块。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-21
    • 1970-01-01
    • 1970-01-01
    • 2022-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多