在多个组件上使用service.ts变量

时间:2019-06-05 19:53:13

标签: html angular typescript

我已经用3个变量(用户,操作,休息)设置了next.service.ts,并设置了setters(updateNext())和getters(getUser,getAction,getRest)。我必须使用setter来更改一个组件(库存管理组件)中的变量,并在另一个组件(库存记录组件)中检索这些变量,但是我似乎无法从另一个组件(库存记录)中检索它们填充的组件)。

我曾尝试在getter中返回一个字符串(“ TEST”),但它确实有效,但是当我尝试返回一个变量时,它只是不返回任何内容/空字符串。


export class NextService {
  private action: string;
  private user: string;
  private restraunt: string;

  constructor() { }

  updateNext(actions, users, restraunts) {
    this.action = actions;
    this.user = users;
    this.restraunt = restraunts;
  }

  getAction(): string {
    return this.action;
  }

  getUser(): string {
    return this.user;
  }

  getRest(): string {
    return this.restraunt;
  }
export class InventoryRecordComponent implements OnInit {
  name = '';
  rest = '';
  action = '';

  constructor(private next: NextService) {
    this.name = this.next.getUser();
    this.action = this.next.getAction();
    this.rest = this.next.getRest();
  }

  ngOnInit() {
    document.getElementById('dne').style.display = 'none';
  }

  onSubmit(f: NgForm) {
    const x = document.getElementById('dne');
    if (!this.next.updateCode(this.code)) {
      x.style.display = 'block';
      f.resetForm();
    } else {
      this.next.updateCode(this.code);
      location.replace('inventory-record/qty');
    }
  }
}
export class InventoryRecordFilledComponent implements OnInit {
  name: string;
  action: string;
  rest: string;

  constructor(private next: NextService) {
    this.name = this.next.getUser();
    this.action = this.next.getAction();
    this.rest = this.next.getRest();
   }

  ngOnInit() {

  }
}

每个组件都有各自的html文件,并带有

{{name}} {{action}} {{rest}}

1 个答案:

答案 0 :(得分:0)

如果您需要组件表现为Simpleton(无论在应用程序中的何处使用,该组件都包含相同的值),则必须将其providedIn的值设置为"root",如下所示:

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

@Injectable({
  providedIn: 'root',
})
export class NextService {
  // The rest of the code stays the same
}

对此的描述可以在这里找到:https://angular.io/guide/singleton-services#providing-a-singleton-service

如果您不这样做,则每个导入NextService的组件都将拥有自己的NextService实例,并具有自己的隔离值。如果您希望服务的值在使用该服务的任何地方都可用,那么您希望该服务是Simpleton,因此必须遵循以下步骤。

遵循上述步骤并不是将组件简化为Simpleton的唯一方法,但是正如链接所提到的,这是实现此目的的首选方法。

希望有帮助!