如何在角中创建Getter的Setter

问题描述 投票:0回答:2

我正在使用Angular7。我想在打字稿中获取并设置变量

我的代码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();
  }
}

我希望在[[Login.Component.ts中设置值,并在Customer.Component.ts]中获取值如何运作或其他运作?

我正在使用Angular7。我想在打字稿中获取并设置变量。我的代码login.service.ts import'Injectable} from'@ angular / core'; @Injectable({{provedIn:'root'})导出类...

angular typescript getter-setter
2个回答
7
投票
1)确保您的login.component.ts文件也注入了服务。

0
投票
您只需要具有两个相同的功能,一个具有前缀集,另一个具有前缀get:
© www.soinside.com 2019 - 2024. All rights reserved.