英文:
How to set a global variable that can be accessed between components?
问题
在login.component.ts文件中,您可以通过以下方式创建一个全局变量来存储用户输入的用户名,以便在buyback.component.ts文件中访问和与其他变量一起使用:
**login.component.ts**
```typescript
import { Component, OnInit, ViewChild } from '@angular/core';
import { NgForm, FormGroup, FormControl } from '@angular/forms';
import { Router } from '@angular/router';
import { Location } from '@angular/common';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
@ViewChild('ngForm') ngForm: NgForm;
loginForm = new FormGroup({
userName: new FormControl(),
userPass: new FormControl()
});
userError: boolean = false;
passError: boolean = false;
// 在这里创建全局变量存储用户名
globalUserName: string; // 新代码
constructor(private router: Router, private location: Location) { }
ngOnInit() {
if (sessionStorage.length != 0) {
this.location.replaceState('/tool');
this.router.navigate(['/tool']);
}
}
submitForm() {
if (this.loginForm.value.userPass == null &&
this.loginForm.value.userName == null) {
this.userError = true;
this.passError = true;
setTimeout(() => {
this.userError = false;
this.passError = false;
}, 4000);
} else {
if (this.loginForm.value.userName != "" &&
this.loginForm.value.userPass != "") {
// 将用户名存储到全局变量
this.globalUserName = this.loginForm.value.userName; // 新代码
sessionStorage.setItem(this.loginForm.value.userName, this.loginForm.value.userPass);
localStorage.setItem("user", JSON.stringify(this.loginForm.value.userName));
let userName = JSON.parse(localStorage.getItem("user"));
this.location.replaceState('/tool');
this.router.navigate(['/tool']);
}
}
}
}
现在,您可以在buyback.component.ts文件中通过访问this.globalUserName
来获取用户输入的用户名,然后与其他变量一起使用。
export class BuybackComponent implements OnInit {
constructor(private _buybackService: BuybackService, private router: Router, private location: Location) { }
userName: String; // 在这里存储用户名
arbNumber: String;
arbNumber2: String;
bType: String;
optionValue: String;
choice: String;
buybackAmt: String;
buybackTypeChoice: String
// 其他变量
ngOnInit() {
// 可以在这里使用this.userName和其他变量
}
}
<details>
<summary>英文:</summary>
https://i.stack.imgur.com/mx3mN.png
Heres a picture of the structure of the project
In login.component.html I have code to obtain the username via user input from a standard login screen:
**Login.component.html**
<form [formGroup]="loginForm" #ngForm="ngForm" (ngSubmit)="submitForm()" class="login-form">
<mat-card-content>
<p class="content">Username:<span>*</span></p>
<input type="text" formControlName="userName" id="userName" autocomplete="off">
<div class="form-group" *ngIf="userError">
<p class="alert1 alert-danger">
<strong>Required: </strong>Username
that username is followed up in login.component.ts like so:
**login.component.ts**
.....
import { Component, OnInit, ViewChild } from '@angular/core';
import { NgForm, FormGroup, FormControl } from '@angular/forms';
import { Router } from '@angular/router';
import { Location } from '@angular/common';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
@ViewChild('ngForm') ngForm: NgForm;
loginForm = new FormGroup({
userName: new FormControl(),
userPass: new FormControl()
});
userError: boolean = false;
passError: boolean = false;
constructor(private router: Router, private location: Location) { }
ngOnInit() {
if (sessionStorage.length != 0) {
this.location.replaceState('/tool');
this.router.navigate(['/tool']);
}
}
submitForm() {
if ((this.loginForm.value.userPass == null &&
this.loginForm.value.userName == null)) {
this.userError = true;
this.passError = true;
setTimeout(() => {
this.userError = false;
this.passError = false;
}, 4000);
......
//New Code
else {
if (this.loginForm.value.userName != "" && this.loginForm.value.userPass != "") {
sessionStorage.setItem(this.loginForm.value.userName, this.loginForm.value.userPass);
localStorage.set("user", JSON.stringify(this.loginForm.value.userName)); // new code inserted here
let userName = JSON.parse(localStorage.get("user")); //and here
this.location.replaceState('/tool');
this.router.navigate(['/tool']);
}
}
}
What I'm trying to do is create a global variable that would allow me to access username from login.component.ts and interact with it in buyback.component.ts. I think I need to create a global variable for the username in the login.component.ts file within the submitForm code but I don't know how.
How can I code a global variable that would allow me to take what the user inputs as their username in login.component.html and ts file and interact with that data in buyback.component.ts alongside other variables like arbNumber, choice, buybackType, etc (that can be viewed in code below..)
**buyback.component.ts**
....
export class BuybackComponent implements OnInit {
constructor(private _buybackService: BuybackService, private router: Router, private location: Location) { }
userName:String; //new code
arbNumber:String;
arbNumber2:String;
bType:String;
optionValue:String;
choice:String;
buybackAmt:String;
buybackTypeChoice:String
.....
</details>
# 答案1
**得分**: 1
在Angular中,您有一些方法可以共享全局内容。最佳实践是使用一个简单的服务。 `ng g s shared-data`
该服务可以如下所示:
```typescript
export class SharedService {
private userData: { userName: string, role: string };
public getUser() {
return this.userData;
}
public setUser(userData: any) {
this.userData = userData;
}
}
```
并且在任何组件中,您可以这样做:
```typescript
constructor(private sharedData: SharedData) {}
getUser() {
this.sharedData.getUser(); // 就是这里!
}
```
但保存用户名称、令牌、角色等数据的最佳方式可能是浏览器本地存储:
```typescript
localStorage.set("user", JSON.stringify(userData)); // 也可以是一个简单的字符串
let user = JSON.parse(localStorage.get("user"));
```
<details>
<summary>英文:</summary>
In Angular you have some ways to share global things. The best practice is to use a simple service. `ng g s shared-data`
The service can look like this:
```
export class SharedService {
private userData: { userName: string, role: string };
public getUser() {
return this.userData;
}
public setUser(userData: any) {
this.userData = userData;
}
}
```
And in any component you can do this:
```
constructor(private sharedData: SharedData) {}
getUser() {
this.sharedData.getUser(); // Here it is!
}
```
But the best way to save data like user name, token, role and so on can be the browser local storage:
```
localStorage.set("user", JSON.stringify(userData)); // can be a simple string, too
let user = JSON.parse(localStorage.get("user"));
```
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论