登录 ionic 5 后更新侧边菜单



用户登录后,我必须更新侧边菜单中的数据。我正在使用Ionic 5。这是我的app.component.ts,它有侧边菜单。

import { Component, OnInit, Inject, NgZone } from '@angular/core';
import { Router } from '@angular/router';
import { Platform } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { NavController } from '@ionic/angular';

import { TranslateService } from '@ngx-translate/core';
import { APP_CONFIG, AppConfig } from './app.config';
import { MyEvent } from 'src/services/myevent.services';
import { Constants } from 'src/models/contants.models';
import { ApisService } from 'src/app/services/apis.service';
import { UtilService } from 'src/app/services/util.service';
import { Subject } from 'rxjs';


@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss']
})
export class AppComponent implements OnInit {
rtlSide = "left";
showLogout:any=false;
username: any;
userno: any; 
public selectedIndex = 0;
public appPages = [
{
title: 'Home',
sub_title: 'Yummy Foods',
url: '/home',
icon: 'zmdi zmdi-store ion-text-start'
},
{
title: 'My Orders',
sub_title: 'Foods to your tummy',
url: '/myorders',
icon: 'zmdi zmdi-cutlery ion-text-start'
},
{
title: 'My Profile',
sub_title: 'Who am i?',
url: '/myprofile',
icon: 'zmdi zmdi-pin-account ion-text-start'
},
{
title: 'Reviews',
sub_title: 'Hows food?',
url: '/review',
icon: 'zmdi zmdi-ticket-star ion-text-start'
},
{
title: 'Contact Us',
sub_title: 'Let us know your queries and feedbacks',
url: '/contact',
icon: 'zmdi zmdi-comment-text ion-text-start'
},
{
title: 'Exit',
sub_title: 'Come back soon',
icon: 'zmdi zmdi-alert-triangle ion-text-start'
}
];

constructor(
@Inject(APP_CONFIG) public config: AppConfig,
private platform: Platform, private navCtrl: NavController,
private splashScreen: SplashScreen,
private statusBar: StatusBar,
private ngZone: NgZone,
private util: UtilService,
private apis: ApisService,
private translate: TranslateService, private myEvent: MyEvent) {
this.initializeApp();
this.myEvent.getLanguageObservable().subscribe(value => {
this.navCtrl.navigateRoot(['./']);
this.globalize(value);
});
}

loadProfile() {
this.apis.checkAuth().then((user) => {
if (user) {
this.getProfile();
}
}).catch(error => {
console.log(error);
});
}



initializeApp() {
this.platform.ready().then(() => {
this.statusBar.styleDefault();
this.splashScreen.hide();

let defaultLang = window.localStorage.getItem(Constants.KEY_DEFAULT_LANGUAGE);
this.globalize(defaultLang);
});
}

globalize(languagePriority) {
this.translate.setDefaultLang("en");
let defaultLangCode = this.config.availableLanguages[0].code;
this.translate.use(languagePriority && languagePriority.length ? languagePriority : defaultLangCode);
this.setDirectionAccordingly(languagePriority && languagePriority.length ? languagePriority : defaultLangCode);
}

setDirectionAccordingly(lang: string) {
switch (lang) {
case 'ar': {
this.rtlSide = "rtl";
break;
}
default: {
this.rtlSide = "ltr";
break;
}
}
}

ngOnInit() {
const path = window.location.pathname.split('folder/')[1];
if (path !== undefined) {
this.selectedIndex = this.appPages.findIndex(page => page.title.toLowerCase() === path.toLowerCase());
}
this.getProfile();

}

ionViewWillEnter() {
this.getProfile();
}

ionViewDidLoad()
{
this.getProfile();
}

my_profile() {
this.navCtrl.navigateRoot(['./myprofile']);
}

getProfile() {
this.apis.getMyProfile(localStorage.getItem('uid')).then((data: any) => {
console.log('userdata', data);
if (data) {
this.ngZone.run(() => {
this.username = data.fullname;
this.userno = data.phone;
});

}
}).catch(error => {
console.log(error);
});
}

}

我需要在用户登录后更新侧菜单中的姓名和电话号码。这是登录.page.ts 中的登录方法

onLogin(form: NgForm) {
console.log('form', form);
this.submitted = true;
if (form.valid) {
const emailfilter = /^[w._-]+[+]?[w._-]+@[w.-]+.[a-zA-Z]{2,6}$/;
if (!emailfilter.test(this.login.email)) {
this.util.showToast(this.util.translate('Please enter valid email'), 'danger', 'bottom');
return false;
}
console.log('login');
this.isLogin = true;
this.api.login(this.login.email, this.login.password).then((userData) => {
console.log(userData);
this.api.getProfile(userData.uid).then((info) => {
console.log(info);
if (info && info.status === 'active') {
localStorage.setItem('uid', userData.uid);
localStorage.setItem('help', userData.uid);
localStorage.setItem('uname', userData.fullname);
localStorage.setItem('unumber', userData.phone);
this.isLogin = false;
this.util.publishLoggedIn('LoggedIn');
// this.navCtrl.back();
this.router.navigate(['home']);
} else {
Swal.fire({
title: this.util.translate('Error'),
text: this.util.translate('Your are blocked please contact administrator'),
icon: 'error',
showConfirmButton: true,
showCancelButton: true,
confirmButtonText: this.util.translate('Need Help?'),
backdrop: false,
background: 'white'
}).then(data => {
if (data && data.value) {
localStorage.setItem('help', userData.uid);
this.router.navigate(['inbox']);
}
});
}
}).catch(err => {
console.log(err);
this.util.showToast(`${err}`, 'danger', 'bottom');
});
}).catch(err => {
if (err) {
console.log(err);
this.util.showToast(`${err}`, 'danger', 'bottom');
}
}).then(el => this.isLogin = false);
}
}

我想过使用事件,但在离子 5 事件中 API 已被弃用。谁能帮我解决这个问题?

我使用行为主体来实现这一点。在我的服务类中,我有一个类AuthInfo。

export class AuthInfo {
constructor(public $uid: string) { }
isLoggedIn() {
return !!this.$uid;
}
}

然后我为未知用户声明一个变量和一个行为主体变量

static UNKNOWN_USER = new AuthInfo(null);
public authInfo$: BehaviorSubject<AuthInfo> = new BehaviorSubject<AuthInfo>(ApisService.UNKNOWN_USER);

然后是登录用户的方法:

public login(email: string, password: string): Promise<any> {
return new Promise<any>((resolve, reject) => {
this.fireAuth.auth.signInWithEmailAndPassword(email, password)
.then(res => {
if (res.user) {
this.db.collection('users').doc(res.user.uid).update({
fcm_token: localStorage.getItem('fcm') ? localStorage.getItem('fcm') : ''
});
this.authInfo$.next(new AuthInfo(res.user.uid));
resolve(res.user);
}
})
.catch(err => {

this.authInfo$.next(ApisService.UNKNOWN_USER);
reject(`login failed ${err}`);
});
});
}

最后在app.component.ts文件的ngOnInit方法中,

this.apis.authInfo$.subscribe((data) => {
console.log('userData',data);
this.userID = data.$uid;
console.log('Userd id from behaviour subject', this.userID);
this.loadProfile();
console.log("called get profile after behaviour subject");
});

这将实时更新侧边菜单中的数据

相关内容

  • 没有找到相关文章

最新更新