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



我已经设置了next.service.ts,其中包含3个变量(user,action,rest(,并制作了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 }}

如果您需要组件表现为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 的唯一方法,但正如链接所述,这是执行此操作的首选方法。

希望对您有所帮助!

相关内容

最新更新