Angular Service单例构造函数多次调用 [英] Angular Service singleton constructor called multiple times

查看:184
本文介绍了Angular Service单例构造函数多次调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用一个应用程序范围的服务(UserService),该服务存储经过身份验证的用户详细信息.我已经设置了一些路由,但是发现UserService是按路由实例化的.我希望他们共享相同的UserService.

I am trying to use an app-wide service (UserService) that stores authenticated user details. I have set up some routes but found that UserService is instantiated per route. I want them to share the same UserService.

我创建了一个包含TestService作为提供程序的CoreModule,并将其导入到AppModule中.

I have created a CoreModule containing TestService as provider and imported it into AppModule.

core.module.ts:

core.module.ts:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TestService } from '../test.service';

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [],
  providers: [
    TestService
  ]
})
export class CoreModule { }

test.service.ts:

test.service.ts:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class TestService {
  constructor() { console.log('testService constructor called');}
}

app.module.ts

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AdminComponent } from './layout/admin/admin.component';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';


import { CoreModule } from './core/core.module';

@NgModule({
  declarations: [
    AppComponent,
    AdminComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    CoreModule
  ],
  providers: [
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

app-routing.module.ts

app-routing.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';
import { BasicLoginComponent } from './basic-login/basic-login.component';
import { HttpClientModule } from '@angular/common/http';
import { AdminComponent } from './layout/admin/admin.component';    

const routes: Routes = [
  {
    path: '',
    component: AdminComponent,
    children: [
      {
        path: 'home',
        loadChildren: './dashboard/dashboard.module#DashboardModule'
      },
      {
        path: 'user/profile',
        loadChildren: './user-profile/user-profile.module#UserProfileModule'
      }
    ]

  },
]
@NgModule({
  imports: [
    CommonModule,
    RouterModule.forRoot(routes),
    HttpClientModule
  ],
  exports: [
    [RouterModule]
  ],
  declarations: []
})
export class AppRoutingModule { }

我已经将TestService注入DashboardComponent和UserProfileComponent构造函数中.但是,当在其中两个组件之间路由时,TestService构造函数将被调用两次.

I have injected the TestService into DashboardComponent and UserProfileComponent constructors. However, when routing between two of these components, the TestService constructor is called twice.

这似乎很简单,但是我却无法正确解决.谁能为我指出正确的方向进行故障排除?

It seems so straightforward but somehow I can't get it right. Can anyone point me to the right direction to troubleshoot this?

*编辑

dashboard.component.ts

dashboard.component.ts

import {AfterViewInit, Component, OnInit, ViewEncapsulation} from '@angular/core';
/*import {NotificationsService} from 'angular2-notifications';*/

import { UserService } from '../user.service.js';
import { LocalStorageService } from '../../../node_modules/ngx-webstorage';
import { TestService } from '../test.service.js';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class DashboardComponent implements OnInit, AfterViewInit {


  constructor(private userService:UserService, private localSt:LocalStorageService,
  private testService:TestService) { // private servicePNotify: NotificationsService
  }


  ngOnInit() {

  }

}

user-profile-component.ts:

user-profile-component.ts:

import {Component, OnInit} from '@angular/core';
import {animate, style, transition, trigger} from '@angular/animations';
import {Http} from '@angular/http';
import { TestService } from '../test.service';

@Component({
  selector: 'app-user-profile',
  templateUrl: './user-profile.component.html',
  styleUrls: [
    './user-profile.component.scss',
    '../../assets/icon/icofont/css/icofont.scss'
  ],

})
export class UserProfileComponent implements OnInit {

  constructor(public http: Http, private userService: UserService,
  private testService:TestService) {
  }

  ngOnInit() {

  }

}

推荐答案

您已将TestService声明为-

As you have declared the TestService as -

@Injectable({
  providedIn: 'root'
})

这意味着您要添加到AppRoot模块.

Which means you are adding to AppRoot module.

无需在CoreModule中显式添加,因此从CoreModule的提供者中删除.删除以下内容-

No need to add explicitly in the CoreModule, so remove from providers of CoreModule. Remove following -

providers: [
    TestService
  ]

当您在RootModule中已经添加的CoreModule中添加TestSevice时,这就是constructor被多次调用的原因.

As you are adding the TestSevice in CoreModule which is already added in RootModule that's the reason it constructor getting called multiple times.

因此,请使用上方的任意一个.

So use either of one from above.

这篇关于Angular Service单例构造函数多次调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆