如何在使用angular开发的整个应用程序中访问用户名?

问题描述 投票:0回答:3

我目前正在使用Angular,Express和MySQL开发应用程序。我想从数据库中提取一个用户名,并将其传递给前端,并在正确执行用户登录功能时在整个应用程序用户区域访问它。我有点知道我可以使用service.ts文件来执行此操作,但是我不知道该怎么做。我可以帮忙吗?

angular service username
3个回答
0
投票

服务的优势在于应用程序的生命周期。由于服务只是一个类,因此您可以使用带有变量的服务来存储值

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class DataService {

  userName;
  constructor(httpClient:HttpClient) { }

  getUserName(user:string,password:String)
  {
      this.post('...your..api...',{user:user,password:password).pipe(tap(
           res=>{
               if (res==true)
                   this.userName=userName
           }
      ))
  }

}

我支持您的网址,其网址为{username:...,password:...},如果已记录则返回true,否则返回false

注入此服务的所有组件,都可以使用和更改变量“ userName”。如果要在.html中查看,请在构造函数中将变量声明为public

constructor(public dataService:DataService){}

//and in the .html
{{dataService.userName}}

0
投票

您可以使用会话或本地存储

设置用户:

let key = 'user'; 
let value = {};
sessionStorage.setItem(key, value);

检索用户:

const user= sessionStorage.getItem(key);

0
投票
  1. 按照您所说的创建AuthService.ts
  2. 在您的服务内部定义用户信息类型的可观察对象(可以是BehaviourSubject)
  3. 在获得用户信息的api服务中,在已定义的可观察对象上注入AuthService的使用,以使用接收到的数据更新所有订阅者(或服务中定义的方法调用)
  4. 将服务注入您需要用户信息/个人资料的组件中
  5. 在组件中订阅该可观察项
interface UserInfo {
  email: string;
  dob: string;
};

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  UserInfo: BehaviorSubject<UserInfo> = new BehaviorSubject(null);

  updateUserInfo(data: UserInfo) {
    this.UserInfo.next(data);
  }

}

在api服务中,您将获得使用接收到的数据调用updateInfo的用户信息(您必须将auth服务添加到api服务构造函数中,并使用访问修饰符private,protected,public以通过angular注入它)

在组件中:

export class HeaderComponent implements OnInit {
  u: UserInfo;

  constructor(private authService: AuthService) { }

  ngOnInit() {
    this.authService.UserInfo.subscribe(x=>this.u=x)
  }

}

现在您可以绑定到组件中的“ u”字段。

© www.soinside.com 2019 - 2024. All rights reserved.