Lon*_*yễn 0 getter-setter typescript angular
我正在使用Angular7。我想在打字稿中获取并设置变量
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;
}
}
Run Code Online (Sandbox Code Playgroud)
fLogin(user, pass) {
this.users.setUser=user;
}
Run Code Online (Sandbox Code Playgroud)
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();
}
}
Run Code Online (Sandbox Code Playgroud)
我希望在Login.Component.ts中设置值,并在Customer.Component.ts中获取值
它如何工作或其他工作?
1)确保您的login.component.ts文件也注入了服务。
constructor(public user:LoginService)
Run Code Online (Sandbox Code Playgroud)
2)确保没有模块或组件具有providers包含您的服务的数组。
如果您按providedIn: 'root'原样使用来注册服务,并且不以任何providers数组形式再次注册该服务,则该服务应为单例并且可以按预期工作。
另外,您的吸气剂和吸气剂的命名是不正确的。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;
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以像访问其他任何声明的属性一样访问那些getter / setter属性。
this.fullName = "Joe Smith"; // to set the value and call the setter
console.log(this.fullName); // to reference the value.
Run Code Online (Sandbox Code Playgroud)
在您的客户组件中:
constructor(public loginService:LoginService) {
}
loadData() {
console.log(this.loginService.user)
}
Run Code Online (Sandbox Code Playgroud)
注意:我重命名了您的构造函数参数,以更好地识别它。
在您的登录组件中:
constructor(public loginService:LoginService) {
}
fLogin(user, pass) {
this.loginService.user = user;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7156 次 |
| 最近记录: |