简体   繁体   English

在另一个单例服务中创建的 Angular 单例服务的新实例

[英]New instance of Angular singleton service being created in another singleton service

I am new to Angular and am trying to figure out how to inject my Angular service (game service) into another angular service which will be a Resolver (game resolver).我是 Angular 的新手,正在尝试弄清楚如何将我的 Angular 服务(游戏服务)注入到另一个将成为解析器(游戏解析器)的 Angular 服务中。 Only one instance of my game service is typically created in my application and I am injecting it into each of my components successfully, but when my game resolver service is needed, it creates a new instance of the game service, even though the game service is supposed to be a singleton.我的应用程序中通常只创建了一个游戏服务实例,并且我成功地将它注入到我的每个组件中,但是当需要我的游戏解析器服务时,它会创建游戏服务的一个新实例,即使游戏服务是应该是单身。

I've tried declaring both services in the 'providers' array of my NgModule, to try to make them both singleton services and I've also tried the approach of of declaring 'providedIn: 'root' in the @Injectable decorator, but a new instance of the game service is created when the game resolver service constructor is called.我尝试在我的 NgModule 的“providers”数组中声明这两个服务,以尝试使它们都是单例服务,并且我还尝试了在 @Injectable 装饰器中声明 'providedIn: 'root' 的方法,但是游戏服务的新实例是在调用游戏解析器服务构造函数时创建的。

//GameResolver.service.ts

    @Injectable({
      providedIn: 'root'
    })
    export class GameResolverService implements Resolve<Game> {
      constructor(private gameService: GameService) {

      }


      resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Game> {

          return this.gameService.getGameById(gameId)

      }
    }

//game-resolver.service.spec.ts    

import { TestBed, inject } from '@angular/core/testing';

import { GameResolverService } from './game-resolver.service';

describe('GameResolverService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [GameResolverService]
    });
  });

  it('should be created', inject([GameResolverService], (service: GameResolverService) => {
    expect(service).toBeTruthy();
  }));
});



//Game.service.ts

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { Game } from './game';
import { map } from "rxjs/operators";
import { User } from './user';


@Injectable({
  providedIn: 'root'
})
export class GameService {

  constructor(private http: Http) {
    console.log('new instance of GameService created');
  }



//app.module.ts

const appRoutes: Routes = [
  ...
  {path:'game', component: GameComponent, data:{depth:3}, resolve: { game: GameResolverService}},
  {path:'endGame', component: EndGameComponent, data:{depth:4}},
  {path:'nextRound', component: NextRoundComponent, data:{depth:5}}
]

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
  ],
  bootstrap: [AppComponent],
  providers: [GameService, GameResolverService]
})


//create-game.component.ts
...
import {GameService} from '../game.service';




@Component({
  selector: 'app-create-game',
  templateUrl: './create-game.component.html',
  styleUrls: ['./create-game.component.css'],

})
export class CreateGameComponent implements OnInit {
  // @HostListener('window:popstate', ['$event'])




  constructor(private gameService: GameService, private router: Router) {
   }


//game.component.ts

@Component({
  selector: 'app-game',
  templateUrl: './game.component.html',
  styleUrls: ['./game.component.css']
})
export class GameComponent implements OnInit {

  game:Game;

  constructor(private gameService: GameService, private router: Router, private socketService: SocketService, private route: ActivatedRoute ) {
    this.game = this.route.snapshot.data['game']
  }
}

Is there something I'm not understanding about the hierarchy of angular dependency injection?关于角度依赖注入的层次结构,我有什么不明白的地方吗? I need the GameService to be a singleton service across all parts of the app, so I need the singleton instance to be injected in the Game Resolver Service without creating a new instance.我需要 GameService 成为跨应用程序所有部分的单例服务,因此我需要将单例实例注入到 Game Resolver Service 中,而无需创建新实例。

I finally realized after much searching that in my app.component.ts file, I still had the providers array defined in the @Component decorator, while I was using the providedIn: 'root' method.经过多次搜索,我终于意识到在我的 app.component.ts 文件中,我仍然在 @Component 装饰器中定义了providers数组,而我正在使用providedIn: 'root'方法。 Dzhavat Ushev was right, you cannot use both of these at the same time. Dzhavat Ushev 是对的,你不能同时使用这两者。 I thought I had gotten rid of all my providers declarations, but I had no idea that one was there.我以为我已经摆脱了我所有的providers声明,但我不知道那里有一个。 It works perfectly now.它现在完美地工作。 Thanks for you help guys.谢谢你们的帮助。

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

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