angular - 服务始终返回构造函数中设置的值

标签 angular angular5

我正在开发一款游戏,只是为了好玩和学习 Angular v5。在我创建的服务中,我在构造函数中设置了一个默认值,有一个 getter 和一个 setter。在 Debug模式下运行项目时,我注意到:

  • 调试器永远不会在构造函数处停止
  • 调用 setter 并将 selectedBoat 设置为与构造函数中不同的值
  • getter 总是返回在构造函数中设置的值。
  • 服务被注入(inject)到 2 个组件中,一个我称为 setter,另一个称为 getter。

服务代码是:

import { Injectable } from '@angular/core';
import { BoatType } from '../../shared/modules/boatType';

@Injectable()
export class BoatContainerService {
  private boats: number[] = [BoatType.AircraftCarrier, BoatType.Battleship, BoatType.Destroyer, BoatType.PatrolBoat, BoatType.Submarine];
  private selectedBoat: BoatType;

  constructor() { 
    this.selectedBoat = BoatType.Undefined;
  }

  selectBoat(boat: BoatType) {
    this.selectedBoat = boat;
  }

  ignoreSelection() {
    this.selectedBoat = BoatType.Undefined;
  }

  removeBoat(boat: BoatType) {    
    this.boats.slice(boat, boat + 1);
  }

  getSelected() : BoatType {
    return this.selectedBoat;
  }
}

BoatType 是一个枚举:

export enum BoatType {
    Undefined = 1,
    AircraftCarrier,
    Battleship,
    Destroyer,
    Submarine,
    PatrolBoat
}

我尝试将数据类型替换为数字,结果是一样的。

所以,基本上它不起作用,因为即使我调用 selectBoat(...),getSelected() 也始终返回“未定义”。为什么?

最佳答案

这些是将服务添加到提供者列表并注入(inject)的步骤:

将服务添加到模块提供者

import { BoatContainerService } from './boat-container.service';

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

将服务注入(inject)组件

import { Component } from '@angular/core';
import {BoatContainerService} from './boat-container.service'

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  constructor (public BoatContainer:BoatContainerService) { 

  }
}

Add the service to single module(AppModule) will make the service singleton or shared service so will persist the state of the service and will create only once.

在 Angular 6 中,您可以通过在服务 Injectable 装饰器中设置它来跳过将服务添加到 app.module

@Injectable({
  providedIn: 'root',
})
export class BoatContainerService {
  ...
}

stackblitz example

关于angular - 服务始终返回构造函数中设置的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51487947/

相关文章:

Angular 5 编译速度很慢,有时内存不足

angular - 使用自定义名称导出文件

angular - 如何避免在 Angular 中使用 *ngFor?

angular - 从 Angular 5 的输入文本字段中获取值

json - 从 API 中解析 JSON 字符串

angular - 在 typescript Angular 5 中导入 json 文件

checkbox - Angular 5根据条件禁用和启用复选框

angularjs - 我如何在 Http Observable 上使用 "Interval"或类似的?

json - 调用特定路由器 URL 时返回纯 JSON

angular - 如何在 Angular 应用程序中使用路由更改页面标题?