我目前正在使用Angular,Express和MySQL开发应用程序。我想从数据库中提取一个用户名,并将其传递给前端,并在正确执行用户登录功能时在整个应用程序用户区域访问它。我有点知道我可以使用service.ts文件来执行此操作,但是我不知道该怎么做。我可以帮忙吗?
服务的优势在于应用程序的生命周期。由于服务只是一个类,因此您可以使用带有变量的服务来存储值
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}}
您可以使用会话或本地存储
设置用户:
let key = 'user';
let value = {};
sessionStorage.setItem(key, value);
检索用户:
const user= sessionStorage.getItem(key);
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”字段。