如何在 Angular 中创建 Getter Setter

How To Create Getter Setter In Angular

我正在使用 Angular 7. 我想在打字稿中获取和设置变量

我的代码login.service.ts

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

@Injectable({
  providedIn: 'root'
})
export class LoginService {
  public username:string;
  public token:string;
  public fullname:string;
  constructor() { }
  set setUser(val: string){
    this.username = val;
  }
  set setToken(val:string){
    this.token=val;
  }
  set setFullName(val:string){
    this.fullname=val;
  }
  get getUser():string{
    return this.username;
  }
  get getToken():string{
    return this.token;
  }
  get getFullName():string{
    return this.fullname;
  }
}

我的代码在Login.Component.ts

fLogin(user, pass) {
    this.users.setUser=user;
}

我的代码在 Customer.Component.ts

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { Http, Headers } from "@angular/http";
import {LoginService} from "../login.service"
import { NgLocalization } from '@angular/common';
@Component({
  selector: 'app-customers',
  templateUrl: './customers.component.html',
  styleUrls: ['./customers.component.css']
})
export class CustomersComponent implements OnInit {
  constructor(public user:LoginService) {

  }
  loadData() {
    console.log(this.user.getUser)
  }
    ngOnInit() {
    this.loadData();
  }
}

I expect Set Value In Login.Component.ts And Get Value in Customer.Component.ts

How to it working or the other it working?

1) 确保您的 login.component.ts 文件也注入了服务。

constructor(public user:LoginService)

2) 确保没有模块或组件具有包含您的服务的 providers 数组。

如果您按原样使用 providedIn: 'root' 注册服务,并且 在任何 providers 数组中再次注册服务,则service 应该是一个单例并且按你期望的那样工作。

此外,您的 getter 和 setter 的命名不正确。 getter 和 setter 应该具有 相同的 名称,因为它们只是定义 属性:

的另一种方式
  get user():string{
    return this.username;
  }
  set user(val: string){
    this.username = val;
  }
  get token():string{
    return this.token;
  }
  set token(val:string){
    this.token=val;
  }
  get fullName():string{
    return this.fullname;
  }
  set fullName(val:string){
    this.fullname=val;
  }

然后您可以像访问任何其他声明的属性一样访问这些 getter/setter 属性。

 this.fullName = "Joe Smith"; // to set the value and call the setter

 console.log(this.fullName); // to reference the value.

在您的客户组件中:

  constructor(public loginService:LoginService) {

  }
  loadData() {
    console.log(this.loginService.user)
  }

注意:我重命名了您的构造函数参数以便更好地识别它。

在您的登录组件中:

  constructor(public loginService:LoginService) {

  }

  fLogin(user, pass) {
     this.loginService.user = user;
  }

你只需要有 2 个相同的函数,一个带有前缀 set,另一个带有前缀 get:

****in the Service User

private name: string;

public get info() {
  return name;
}

public set info(val) {
  this.name = val;
}


************ usage in other components or services
this.User.info = 'your name'; // for set

const yourName = this.User.info; // for get