我正在使用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;
}
}
fLogin(user, pass) {
this.users.setUser=user;
}
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中获取值
它如何工作或其他工作?
1)确保您的login.component.ts文件也注入了服务。
constructor(public user:LoginService)
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;
}
然后,您可以像访问其他任何声明的属性一样访问那些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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句