如何在Angular中创建Getter Setter
我用的是角度7。我想在typescript中获取并设置变量 我的代码login.service.ts 以及我在Login.Component.ts中的代码 以及我在Customer.Component.ts中的代码 我希望在Login.Component.ts中设置值,并在Customer.Component.ts中获取值 如何使它工作或其他它工作 1) 确保login.component.ts文件也注入服务如何在Angular中创建Getter Setter,angular,typescript,getter-setter,Angular,Typescript,Getter Setter,我用的是角度7。我想在typescript中获取并设置变量 我的代码login.service.ts 以及我在Login.Component.ts中的代码 以及我在Customer.Component.ts中的代码 我希望在Login.Component.ts中设置值,并在Customer.Component.ts中获取值 如何使它工作或其他它工作 1) 确保login.component.ts文件也注入服务 constructor(public user:LoginService) 2) 确
constructor(public user:LoginService)
2) 确保没有模块或组件具有包含您的服务的提供程序阵列
如果您使用“根”
中提供的注册服务,并且不再在任何提供程序
数组中注册该服务,则该服务应为单例服务,并按预期工作
此外,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;
}
注意:我重命名了构造函数参数以更好地识别它
在您的登录组件中:
constructor(public loginService:LoginService) {
}
loadData() {
console.log(this.loginService.user)
}
constructor(public loginService:LoginService) {
}
fLogin(user, pass) {
this.loginService.user = user;
}
您只需要有两个相同的函数,一个带有前缀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
哪个部分返回未定义?考虑添加一个更新到你原来的问题,显示你更新的代码和当前的问题。谢谢你的角度基础课程在多个视野。
****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