我是Angular的新手,正在尝试弄清楚如何将Angular服务(游戏服务)注入另一个将成为Resolver(游戏解析器)的angular服务中。通常,我的应用程序中仅创建了一个游戏服务实例,并且已成功将其注入到每个组件中,但是当需要我的游戏解析器服务时,即使游戏服务是应该是单身人士。
我尝试在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']
}
}
关于角度依赖注入的层次结构,我是否不了解?我需要GameService成为应用程序所有部分的单例服务,因此我需要将单例实例注入Game Resolver Service中,而无需创建新实例。
答案 0 :(得分:0)
经过大量搜索后,我终于意识到,在使用providers
方法的同时,我仍然在@Component装饰器中定义了providedIn: 'root'
数组。 Dzhavat Ushev是正确的,您不能同时使用这两个功能。我以为我已经摆脱了所有的providers
声明,但是我不知道有一个声明。现在,它可以完美运行。谢谢您的帮助。