如何在延迟加载的模块的所有组件之间共享相同的服务实例?

时间:2017-03-10 22:49:08

标签: angular angular2-routing angular2-services angular2-modules

我有一个名为“AppModule”的根模块。 “AppModule”延迟加载其他几个模块,其中一个模块称为“BooksAndRunModule”。我有两个属于“BooksAndRunModule”的组件需要共享我命名为“BooksAndRunService”的服务的同一个实例。我将“BooksAndRunService”声明为提供者的第一个也是唯一一个位于“BooksAndRunModule”中的地方。我想通过这样做我的两个组件可以访问相同的服务实例,但他们没有。显然,我对依赖注入的理解不足。我不希望这个服务可以在应用程序范围内使用,这就是为什么我只将它声明为“BooksAndRunModule”中的提供程序。我不明白什么,我该怎么做才能做到这一点?如果您想在我的项目中看到任何其他文件,请告诉我。

的AppModule:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppRoutingModule } from './app-routing.module';
import { AuthenticationModule } from './authentication/authentication.module';
import { SharedModule } from './shared/shared.module';


import { AppComponent } from './app.component';
import { FriendService } from './friend.service';




@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    AppRoutingModule,
    AuthenticationModule,
    SharedModule,
  ],
  providers: [ FriendService ],
  bootstrap: [AppComponent]
})


export class AppModule { }

BooksAndRunModule:

import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';

import { SharedModule } from '../shared/shared.module';

import { FriendService } from '../friend.service';
import { BooksAndRunCreateComponent } from './books_and_run_create.component';
import { BooksAndRunPlayComponent } from './books_and_run_play.component';
import { BooksAndRunService } from './books_and_run.service';

import { BooksAndRunRouter } from './books_and_run.router';



@NgModule({
  declarations: [
    BooksAndRunCreateComponent,
    BooksAndRunPlayComponent,
  ],
  imports: [
    CommonModule,
    SharedModule,
    BooksAndRunRouter,
  ],
  providers: [  FriendService, BooksAndRunService ],
})


export class BooksAndRunModule { }

BooksAndRunCreateComponent:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { FriendList } from '../friendlist';
import { FriendService } from '../friend.service';
import { BooksAndRunService } from './books_and_run.service';


@Component({
  moduleId: module.id,
  selector: 'books-and-run-create',
  templateUrl: './books_and_run_create.component.html',
  styleUrls: ['./books_and_run_create.component.css'],
})


export class BooksAndRunCreateComponent implements OnInit {
  constructor(public friendService: FriendService, private booksAndRunService: BooksAndRunService, private router: Router) { }

  isRequesting: boolean;
  name: string = 'Aaron';
  friendList: FriendList[] = [];
  players: any[] = [];

  private stopRefreshing() {
    this.isRequesting = false;
  }


  ngOnInit(): void {
    this.booksAndRunService.resetPlayers();
    this.isRequesting = true;
    this.friendService
      .getFriendList()
        .subscribe(
          data => this.friendList = data,
          () => this.stopRefreshing(),
          () => this.stopRefreshing(),
        )
  }

  addPlayer(player): void {
    this.booksAndRunService.addPlayer(player);
    for(var i=0; i<this.friendList.length; i++) {
            if(this.friendList[i].pk === player.pk) {
                this.friendList.splice(i, 1);
            }
        }
    this.players = this.booksAndRunService.getPlayers();
    console.log("Current players are: " + this.players);
  }

  removePlayer(player): void {
    this.booksAndRunService.removePlayer(player);
    this.friendList.push(player);
    this.players = this.booksAndRunService.getPlayers();
    console.log("Current players are: " + this.players)
  }

  goToGame(): void {
    console.log('Going to game with players: ' + this.booksAndRunService.getPlayers());
    this.router.navigate(['/books_and_run/play'])
  }



}

BooksAndRunPlayComponent:

import { Component, OnInit, AfterViewChecked } from '@angular/core';
import { BooksAndRunService } from './books_and_run.service';
import { Score } from './books_and_run.classes';



@Component({
  moduleId: module.id,
  selector: 'books-and-run-play',
  templateUrl: './books_and_run_play.component.html',
  styleUrls: ['./books_and_run_play.component.css'],
})


export class BooksAndRunPlayComponent implements OnInit, AfterViewChecked {
  constructor(public booksAndRunService: BooksAndRunService) { }

  game = { players: []};



  ngOnInit(): void {
    console.log("Initalizing BooksAndRunPlayComponent...")
    console.log("Here are the players: " + this.booksAndRunService.getPlayers())
    var game: any;

    if(localStorage.getItem('game') === null) {
      console.log("Creating a new game...");
      this.game = this.booksAndRunService.prepareGame();
      this.booksAndRunService.saveGame(this.game);
    } else {
        console.log("Restoring game from localStorage...");
        this.game = this.booksAndRunService.restoreGame();
    };

  }

  ngAfterViewChecked() {
    this.booksAndRunService.saveGame(this.game);
  }

}

BooksAndRunService:

import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import { Game, Player, Score, Round } from './books_and_run.classes'


@Injectable()
export class BooksAndRunService {

    players: Player[];

    getPlayers() {
        return this.players;
    }

    addPlayer(player) {
        this.players.push(player);
    }

    removePlayer(player) {
        for(var i=0; i<this.players.length; i++) {
            if(this.players[i].pk === player.pk) {
                this.players.splice(i, 1);
            }
        }
    }

    resetPlayers() {
        this.players = [];
    }

}

3 个答案:

答案 0 :(得分:1)

this question中也提到了同样的问题。接受的答案解决了问题

答案 1 :(得分:0)

BooksAndRunPlayComponent 的构造函数中,将服务设为public,并且不要在 BooksAndRunCreateComponent 中声明它。

跨组件访问并尝试。

或者,将其作为模块级别

static forRoot(): BooksAndRunModule {
        return {
            providers: [BooksAndRunService]
        };
    }

答案 2 :(得分:0)

最简单的答案是在app模块的providers数组中提供此服务。

@NgModule({
    providers: [ BooksAndRunService ]
})
class AppModule {}

在对该主题的官方解释汇编中,here很好地涵盖了这一点。简而言之,延迟加载的模块有自己的根范围。您可以使用forRoot()代替,但这基本上可以完成同样的事情。