angular - 使用 api 登录后,我的应用程序未将数据保存在本地存储中
问题描述
在我的应用程序中,我使用返回令牌和用户名的 api 登录。我想将两者都保存在本地存储中。用户名,我想稍后在应用程序中显示。
它登录,但不保存数据。
我正在使用带角度的 Ionic 4。
app.component.ts:
initializeApp() {
this.platform.ready().then(() => {
this.statusBar.styleDefault();
this.splashScreen.hide();
this.authenticationService.authenticationState.subscribe(state => {
if (state) {
this.authService.storage.get('nameLogued').then((val) => {
this.nameOfUser = val;
})
this.router.navigate(['members', 'home']);
} else {
this.router.navigate(['login']);
}
});
});
}
app.component.html:
<ion-header>
<ion-toolbar>
<ion-title>
<ion-icon name="contact"></ion-icon>
{{nameOfUser}}
</ion-title>
</ion-toolbar>
</ion-header>
身份验证.service.ts:
login(user) {
return this.http.post(this.global.urlAPI + 'api/login', user);
}
login.page.ts:
login(form) {
this.authService.login(form).subscribe(data => {
this.storage.set(this.global.token_key, data['token']);
this.storage.set('nameLogued', data['user'].name);
this.authService.authenticationState.next(true);
this.login_form = this.formBuilder.group({
email: new FormControl(''),
password: new FormControl('')
})
}, (error => {
this.toast.showToastError('There is wrong data.');
}));
}
谢谢!
解决方案
存储数据
const credentialsKey = 'currentUser';
login(loginData: Login): Observable<any> {
return this.http.post<any>('Usermaster/Authenticate', loginData).pipe(
tap(
function (data) {
const storage = loginData.remember ? localStorage : sessionStorage;
storage.setItem(credentialsKey, JSON.stringify(data));
return data;
}
)
);
}
从存储值中获取数据
private getUser() {
const savedCredentials = sessionStorage.getItem(credentialsKey) || localStorage.getItem(credentialsKey);
return JSON.parse(savedCredentials);
}
推荐阅读
- python - Python多处理 - 池
- javascript - 如何安装和开始使用 Vuetify 和 Vue.js 3
- r - 用 R 尽可能快地计算大点云的特征值
- javascript - 如果用户不存在于数据库中,我想打印错误文本
- python - Django:基于类的视图的extra_content不显示任何数据
- angular - 使用存储值返回 Observable
- istio - 特使过滤器拦截上游响应
- google-cloud-platform - GCP 免费试用结算帐户创建卡住
- node.js - 如何使用 sequelize 执行此请求?
- python - DeepSpeech 无法学习波斯语