如何设置一个可以在组件之间访问的全局变量?

huangapple go评论93阅读模式
英文:

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**
  &lt;form [formGroup]=&quot;loginForm&quot; #ngForm=&quot;ngForm&quot; (ngSubmit)=&quot;submitForm()&quot; class=&quot;login-form&quot;&gt;
    &lt;mat-card-content&gt;
      &lt;p class=&quot;content&quot;&gt;Username:&lt;span&gt;*&lt;/span&gt;&lt;/p&gt;
      &lt;input type=&quot;text&quot; formControlName=&quot;userName&quot; id=&quot;userName&quot; autocomplete=&quot;off&quot;&gt;
      &lt;div class=&quot;form-group&quot;  *ngIf=&quot;userError&quot;&gt;
        &lt;p class=&quot;alert1 alert-danger&quot;&gt;
            &lt;strong&gt;Required: &lt;/strong&gt;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&#39;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&#39;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(&quot;user&quot;, JSON.stringify(userData)); // can be a simple string, too

let user = JSON.parse(localStorage.get(&quot;user&quot;));
```

</details>



huangapple
  • 本文由 发表于 2023年3月4日 04:01:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75631422.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定