I have this code (cleaned) in my app.component.ts
import { Component, OnInit, OnDestroy, ViewChild } from '@angular/core';
import { Platform, ToastController, NavController, MenuController, IonRouterOutlet } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import {
Plugins,
LocalNotificationScheduleResult } from '@capacitor/core';
import { AuthService } from './Services/auth.service';
import { Router } from '@angular/router';
import { User } from './Services/user.service';
const { Network, Toast, PushNotifications, LocalNotifications } = Plugins;
import { Socket } from 'ngx-socket-io';
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss']
})
export class AppComponent implements OnInit, OnDestroy {
@ViewChild(IonRouterOutlet, {static: false}) routerOutlet: IonRouterOutlet;
public user: User;
constructor(
private platform: Platform,
private splashScreen: SplashScreen,
private statusBar: StatusBar,
private authService: AuthService,
private socket: Socket,
) {
this.initializeApp();
this.hardwareBackButton();
}
async ngOnInit() {
this.socket.connect();
// local notifications
await LocalNotifications.requestPermissions();
try {
LocalNotifications.addListener('localNotificationReceived', (notification) => {
console.log('Notification: ', notification);
});
LocalNotifications.addListener('localNotificationActionPerformed', (notification) => {
console.log('Notification action performed', notification);
});
} catch (e) {
console.log('Notification errors: ', e);
}
// chat notif
this.socket.fromEvent('oneononemessage').subscribe(async (message: any) => {
console.log('chat message: ', message);
// if (message.msg.message.user.username !== this.user.username) { // if message receiver with auth user is same, show notif
const notifs = LocalNotifications.schedule({
notifications: [
{
title: message.msg.message.user.username,
body: message.msg.message.note,
id: Math.floor(Math.random() * 10),
schedule: { at: new Date(Date.now() + 1000 * 2) },
sound: 'beep.wav',
attachments: null,
actionTypeId: 'OPEN_CHAT',
extra: null
}
]
});
console.log('scheduled notifications', notifs);
// }
});
// chat notif
}
// ionViewWillLeave() {
// this.socket.disconnect();
// }
initializeApp() {
this.platform.ready().then(() => {
this.statusBar.styleDefault();
this.splashScreen.hide();
this.authService.getToken();
});
}
async ionViewDidEnter() {
(await this.authService.user()).subscribe(user => {
this.user = user;
});
}
}
As you see in my code in ngOnInit
I have this line for notifications
if (message.msg.message.user.username !== this.user.username) {
Which currently I commented it as it was returning error.
Issue
As of Ionic life cycle ionViewDidEnter
comes after ngOnInit
so I cannot have access to this.user
data.
Question
How can I have access to this.user
data in ngOnInit
?