Ionic 4 - Simple Login with localStorage
I am new to ionic and jumped onto the beta Ionic 4 apologies if I ask the simplest question. I've implemented a simple login and I am storing the returned user object from my REST api using Ionic Storage
like this (in user.service.ts
):
var url = `${this.APIUrl}/api/Account/Get?email=${login.email}&password=${login.password}&apikey=${this.APIKey}`;
this.CurrentUser = await this.http.get<iUserModel>(url).toPromise();
// Store User Details
this.storage.set("CurrentUser", this.CurrentUser);
If I investigate in my browser I can see that it is stored under Indexed DB:
Now my challenge is to check if user is logged in on my home page. I've tried to use both the constructor
and ngOnInit()
but it seems my home.page.html
is rendering before the call to go fetch user is complete and here is how I've done it (in home.page.ts
):
export class HomePage implements OnInit
{
CurrentUser: any;
constructor(private nav:NavController, private auth: UserService, private alertCtrl: AlertController, private loadingCtrl: LoadingController, private menuCtrl: MenuController)
{
this.menuCtrl.enable(true);
this.APIUrl = this.auth.APIUrl;
this.CurrentUser = this.auth.CurrentUser; // This becomes undefined when page is refreshed whilst LIVE testing in the browser
}
ngOnInit()
{
/*if (this.auth.GetUser() == undefined || (this.auth.GetUser() != undefined && this.auth.GetUser().Id <= 0))
{
this.nav.navigateBack("/login");
}*/
this.SetUser();
}
async SetUser()
{
await this.auth.GetUser();
this.CurrentUser = this.auth.CurrentUser;
}
}
In user.service.ts
:
async GetUser()
{
this.storage.get("CurrentUser").then( (user) =>
{
this.CurrentUser = user;
console.log(user);
});
}
My console.log(user)
does indeed produce results, however when I try to access the CurrentUser
that should now be set in my home.page.html
<ion-header>
<ion-toolbar>
<ion-buttons slot="start">
<ion-menu-button></ion-menu-button>
</ion-buttons>
<ion-title>
Sample Project
</ion-title>
<ion-avatar end>
<img [alt]="CurrentUser.DisplayName" [src]="APIUrl + '' + CurrentUser.Selfie" />
</ion-avatar>
</ion-toolbar>
</ion-header>
it is always undefined. Can anyone please point out what step I am missing?
Thanks in advance...
angular ionic-framework ionic4
add a comment |
I am new to ionic and jumped onto the beta Ionic 4 apologies if I ask the simplest question. I've implemented a simple login and I am storing the returned user object from my REST api using Ionic Storage
like this (in user.service.ts
):
var url = `${this.APIUrl}/api/Account/Get?email=${login.email}&password=${login.password}&apikey=${this.APIKey}`;
this.CurrentUser = await this.http.get<iUserModel>(url).toPromise();
// Store User Details
this.storage.set("CurrentUser", this.CurrentUser);
If I investigate in my browser I can see that it is stored under Indexed DB:
Now my challenge is to check if user is logged in on my home page. I've tried to use both the constructor
and ngOnInit()
but it seems my home.page.html
is rendering before the call to go fetch user is complete and here is how I've done it (in home.page.ts
):
export class HomePage implements OnInit
{
CurrentUser: any;
constructor(private nav:NavController, private auth: UserService, private alertCtrl: AlertController, private loadingCtrl: LoadingController, private menuCtrl: MenuController)
{
this.menuCtrl.enable(true);
this.APIUrl = this.auth.APIUrl;
this.CurrentUser = this.auth.CurrentUser; // This becomes undefined when page is refreshed whilst LIVE testing in the browser
}
ngOnInit()
{
/*if (this.auth.GetUser() == undefined || (this.auth.GetUser() != undefined && this.auth.GetUser().Id <= 0))
{
this.nav.navigateBack("/login");
}*/
this.SetUser();
}
async SetUser()
{
await this.auth.GetUser();
this.CurrentUser = this.auth.CurrentUser;
}
}
In user.service.ts
:
async GetUser()
{
this.storage.get("CurrentUser").then( (user) =>
{
this.CurrentUser = user;
console.log(user);
});
}
My console.log(user)
does indeed produce results, however when I try to access the CurrentUser
that should now be set in my home.page.html
<ion-header>
<ion-toolbar>
<ion-buttons slot="start">
<ion-menu-button></ion-menu-button>
</ion-buttons>
<ion-title>
Sample Project
</ion-title>
<ion-avatar end>
<img [alt]="CurrentUser.DisplayName" [src]="APIUrl + '' + CurrentUser.Selfie" />
</ion-avatar>
</ion-toolbar>
</ion-header>
it is always undefined. Can anyone please point out what step I am missing?
Thanks in advance...
angular ionic-framework ionic4
1
Is CurrentUser really always undefined or does it become a value later on? You could also take a look at APP_INITIALIZER to make angular wait with bootstraping if you want to postpone the rendering of the view until a promise has resolved.
– M4R1KU
2 days ago
@M4R1KU the CurrentUser does get the value set but only after the view has already been rendered... I will use the suggested approach below or your suggestion, thank you for your help...
– Morgs
2 days ago
add a comment |
I am new to ionic and jumped onto the beta Ionic 4 apologies if I ask the simplest question. I've implemented a simple login and I am storing the returned user object from my REST api using Ionic Storage
like this (in user.service.ts
):
var url = `${this.APIUrl}/api/Account/Get?email=${login.email}&password=${login.password}&apikey=${this.APIKey}`;
this.CurrentUser = await this.http.get<iUserModel>(url).toPromise();
// Store User Details
this.storage.set("CurrentUser", this.CurrentUser);
If I investigate in my browser I can see that it is stored under Indexed DB:
Now my challenge is to check if user is logged in on my home page. I've tried to use both the constructor
and ngOnInit()
but it seems my home.page.html
is rendering before the call to go fetch user is complete and here is how I've done it (in home.page.ts
):
export class HomePage implements OnInit
{
CurrentUser: any;
constructor(private nav:NavController, private auth: UserService, private alertCtrl: AlertController, private loadingCtrl: LoadingController, private menuCtrl: MenuController)
{
this.menuCtrl.enable(true);
this.APIUrl = this.auth.APIUrl;
this.CurrentUser = this.auth.CurrentUser; // This becomes undefined when page is refreshed whilst LIVE testing in the browser
}
ngOnInit()
{
/*if (this.auth.GetUser() == undefined || (this.auth.GetUser() != undefined && this.auth.GetUser().Id <= 0))
{
this.nav.navigateBack("/login");
}*/
this.SetUser();
}
async SetUser()
{
await this.auth.GetUser();
this.CurrentUser = this.auth.CurrentUser;
}
}
In user.service.ts
:
async GetUser()
{
this.storage.get("CurrentUser").then( (user) =>
{
this.CurrentUser = user;
console.log(user);
});
}
My console.log(user)
does indeed produce results, however when I try to access the CurrentUser
that should now be set in my home.page.html
<ion-header>
<ion-toolbar>
<ion-buttons slot="start">
<ion-menu-button></ion-menu-button>
</ion-buttons>
<ion-title>
Sample Project
</ion-title>
<ion-avatar end>
<img [alt]="CurrentUser.DisplayName" [src]="APIUrl + '' + CurrentUser.Selfie" />
</ion-avatar>
</ion-toolbar>
</ion-header>
it is always undefined. Can anyone please point out what step I am missing?
Thanks in advance...
angular ionic-framework ionic4
I am new to ionic and jumped onto the beta Ionic 4 apologies if I ask the simplest question. I've implemented a simple login and I am storing the returned user object from my REST api using Ionic Storage
like this (in user.service.ts
):
var url = `${this.APIUrl}/api/Account/Get?email=${login.email}&password=${login.password}&apikey=${this.APIKey}`;
this.CurrentUser = await this.http.get<iUserModel>(url).toPromise();
// Store User Details
this.storage.set("CurrentUser", this.CurrentUser);
If I investigate in my browser I can see that it is stored under Indexed DB:
Now my challenge is to check if user is logged in on my home page. I've tried to use both the constructor
and ngOnInit()
but it seems my home.page.html
is rendering before the call to go fetch user is complete and here is how I've done it (in home.page.ts
):
export class HomePage implements OnInit
{
CurrentUser: any;
constructor(private nav:NavController, private auth: UserService, private alertCtrl: AlertController, private loadingCtrl: LoadingController, private menuCtrl: MenuController)
{
this.menuCtrl.enable(true);
this.APIUrl = this.auth.APIUrl;
this.CurrentUser = this.auth.CurrentUser; // This becomes undefined when page is refreshed whilst LIVE testing in the browser
}
ngOnInit()
{
/*if (this.auth.GetUser() == undefined || (this.auth.GetUser() != undefined && this.auth.GetUser().Id <= 0))
{
this.nav.navigateBack("/login");
}*/
this.SetUser();
}
async SetUser()
{
await this.auth.GetUser();
this.CurrentUser = this.auth.CurrentUser;
}
}
In user.service.ts
:
async GetUser()
{
this.storage.get("CurrentUser").then( (user) =>
{
this.CurrentUser = user;
console.log(user);
});
}
My console.log(user)
does indeed produce results, however when I try to access the CurrentUser
that should now be set in my home.page.html
<ion-header>
<ion-toolbar>
<ion-buttons slot="start">
<ion-menu-button></ion-menu-button>
</ion-buttons>
<ion-title>
Sample Project
</ion-title>
<ion-avatar end>
<img [alt]="CurrentUser.DisplayName" [src]="APIUrl + '' + CurrentUser.Selfie" />
</ion-avatar>
</ion-toolbar>
</ion-header>
it is always undefined. Can anyone please point out what step I am missing?
Thanks in advance...
angular ionic-framework ionic4
angular ionic-framework ionic4
edited 2 days ago
Chris
2,70062555
2,70062555
asked 2 days ago
Morgs
685718
685718
1
Is CurrentUser really always undefined or does it become a value later on? You could also take a look at APP_INITIALIZER to make angular wait with bootstraping if you want to postpone the rendering of the view until a promise has resolved.
– M4R1KU
2 days ago
@M4R1KU the CurrentUser does get the value set but only after the view has already been rendered... I will use the suggested approach below or your suggestion, thank you for your help...
– Morgs
2 days ago
add a comment |
1
Is CurrentUser really always undefined or does it become a value later on? You could also take a look at APP_INITIALIZER to make angular wait with bootstraping if you want to postpone the rendering of the view until a promise has resolved.
– M4R1KU
2 days ago
@M4R1KU the CurrentUser does get the value set but only after the view has already been rendered... I will use the suggested approach below or your suggestion, thank you for your help...
– Morgs
2 days ago
1
1
Is CurrentUser really always undefined or does it become a value later on? You could also take a look at APP_INITIALIZER to make angular wait with bootstraping if you want to postpone the rendering of the view until a promise has resolved.
– M4R1KU
2 days ago
Is CurrentUser really always undefined or does it become a value later on? You could also take a look at APP_INITIALIZER to make angular wait with bootstraping if you want to postpone the rendering of the view until a promise has resolved.
– M4R1KU
2 days ago
@M4R1KU the CurrentUser does get the value set but only after the view has already been rendered... I will use the suggested approach below or your suggestion, thank you for your help...
– Morgs
2 days ago
@M4R1KU the CurrentUser does get the value set but only after the view has already been rendered... I will use the suggested approach below or your suggestion, thank you for your help...
– Morgs
2 days ago
add a comment |
1 Answer
1
active
oldest
votes
As M4R1KU mentioned in the comment you can look at APP_INITIALIZER
But also I can suggest you one solution. I believe you have something like AppComponent (or just App) in your project (try looking at src/app
folder)
And there you can do something like this:
constructor(private platform: Platform, private auth: UserService) {
this.initializeApp();
}
initializeApp() {
this.platform.ready().then(() => {
this.auth.GetUser();
});
}
Thanks @KidThePug this worked for me...
– Morgs
2 days ago
is me checking in EVERY page'sconstructor
orngOnInit
ifCurrentUser
object is set to determine if user is logged in the best way to check if a user is logged in Ionic? I am coming from a .NET background and would be keen for things such as[Authorize]
attributes.
– Morgs
2 days ago
@Morgs if I understand you correctly, you need to check if user is logged in to determine if he can access some page, correct? You can check guards, they will do the job. Also keep in mind that this tutorial is for ionic 3, if you are using ionic 4 you can reference this article
– KidThePug
yesterday
thanks a lot for the Ionic 4 link, it'll help me quite a lot...
– Morgs
yesterday
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53945426%2fionic-4-simple-login-with-localstorage%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
As M4R1KU mentioned in the comment you can look at APP_INITIALIZER
But also I can suggest you one solution. I believe you have something like AppComponent (or just App) in your project (try looking at src/app
folder)
And there you can do something like this:
constructor(private platform: Platform, private auth: UserService) {
this.initializeApp();
}
initializeApp() {
this.platform.ready().then(() => {
this.auth.GetUser();
});
}
Thanks @KidThePug this worked for me...
– Morgs
2 days ago
is me checking in EVERY page'sconstructor
orngOnInit
ifCurrentUser
object is set to determine if user is logged in the best way to check if a user is logged in Ionic? I am coming from a .NET background and would be keen for things such as[Authorize]
attributes.
– Morgs
2 days ago
@Morgs if I understand you correctly, you need to check if user is logged in to determine if he can access some page, correct? You can check guards, they will do the job. Also keep in mind that this tutorial is for ionic 3, if you are using ionic 4 you can reference this article
– KidThePug
yesterday
thanks a lot for the Ionic 4 link, it'll help me quite a lot...
– Morgs
yesterday
add a comment |
As M4R1KU mentioned in the comment you can look at APP_INITIALIZER
But also I can suggest you one solution. I believe you have something like AppComponent (or just App) in your project (try looking at src/app
folder)
And there you can do something like this:
constructor(private platform: Platform, private auth: UserService) {
this.initializeApp();
}
initializeApp() {
this.platform.ready().then(() => {
this.auth.GetUser();
});
}
Thanks @KidThePug this worked for me...
– Morgs
2 days ago
is me checking in EVERY page'sconstructor
orngOnInit
ifCurrentUser
object is set to determine if user is logged in the best way to check if a user is logged in Ionic? I am coming from a .NET background and would be keen for things such as[Authorize]
attributes.
– Morgs
2 days ago
@Morgs if I understand you correctly, you need to check if user is logged in to determine if he can access some page, correct? You can check guards, they will do the job. Also keep in mind that this tutorial is for ionic 3, if you are using ionic 4 you can reference this article
– KidThePug
yesterday
thanks a lot for the Ionic 4 link, it'll help me quite a lot...
– Morgs
yesterday
add a comment |
As M4R1KU mentioned in the comment you can look at APP_INITIALIZER
But also I can suggest you one solution. I believe you have something like AppComponent (or just App) in your project (try looking at src/app
folder)
And there you can do something like this:
constructor(private platform: Platform, private auth: UserService) {
this.initializeApp();
}
initializeApp() {
this.platform.ready().then(() => {
this.auth.GetUser();
});
}
As M4R1KU mentioned in the comment you can look at APP_INITIALIZER
But also I can suggest you one solution. I believe you have something like AppComponent (or just App) in your project (try looking at src/app
folder)
And there you can do something like this:
constructor(private platform: Platform, private auth: UserService) {
this.initializeApp();
}
initializeApp() {
this.platform.ready().then(() => {
this.auth.GetUser();
});
}
answered 2 days ago
KidThePug
363
363
Thanks @KidThePug this worked for me...
– Morgs
2 days ago
is me checking in EVERY page'sconstructor
orngOnInit
ifCurrentUser
object is set to determine if user is logged in the best way to check if a user is logged in Ionic? I am coming from a .NET background and would be keen for things such as[Authorize]
attributes.
– Morgs
2 days ago
@Morgs if I understand you correctly, you need to check if user is logged in to determine if he can access some page, correct? You can check guards, they will do the job. Also keep in mind that this tutorial is for ionic 3, if you are using ionic 4 you can reference this article
– KidThePug
yesterday
thanks a lot for the Ionic 4 link, it'll help me quite a lot...
– Morgs
yesterday
add a comment |
Thanks @KidThePug this worked for me...
– Morgs
2 days ago
is me checking in EVERY page'sconstructor
orngOnInit
ifCurrentUser
object is set to determine if user is logged in the best way to check if a user is logged in Ionic? I am coming from a .NET background and would be keen for things such as[Authorize]
attributes.
– Morgs
2 days ago
@Morgs if I understand you correctly, you need to check if user is logged in to determine if he can access some page, correct? You can check guards, they will do the job. Also keep in mind that this tutorial is for ionic 3, if you are using ionic 4 you can reference this article
– KidThePug
yesterday
thanks a lot for the Ionic 4 link, it'll help me quite a lot...
– Morgs
yesterday
Thanks @KidThePug this worked for me...
– Morgs
2 days ago
Thanks @KidThePug this worked for me...
– Morgs
2 days ago
is me checking in EVERY page's
constructor
or ngOnInit
if CurrentUser
object is set to determine if user is logged in the best way to check if a user is logged in Ionic? I am coming from a .NET background and would be keen for things such as [Authorize]
attributes.– Morgs
2 days ago
is me checking in EVERY page's
constructor
or ngOnInit
if CurrentUser
object is set to determine if user is logged in the best way to check if a user is logged in Ionic? I am coming from a .NET background and would be keen for things such as [Authorize]
attributes.– Morgs
2 days ago
@Morgs if I understand you correctly, you need to check if user is logged in to determine if he can access some page, correct? You can check guards, they will do the job. Also keep in mind that this tutorial is for ionic 3, if you are using ionic 4 you can reference this article
– KidThePug
yesterday
@Morgs if I understand you correctly, you need to check if user is logged in to determine if he can access some page, correct? You can check guards, they will do the job. Also keep in mind that this tutorial is for ionic 3, if you are using ionic 4 you can reference this article
– KidThePug
yesterday
thanks a lot for the Ionic 4 link, it'll help me quite a lot...
– Morgs
yesterday
thanks a lot for the Ionic 4 link, it'll help me quite a lot...
– Morgs
yesterday
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53945426%2fionic-4-simple-login-with-localstorage%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
Is CurrentUser really always undefined or does it become a value later on? You could also take a look at APP_INITIALIZER to make angular wait with bootstraping if you want to postpone the rendering of the view until a promise has resolved.
– M4R1KU
2 days ago
@M4R1KU the CurrentUser does get the value set but only after the view has already been rendered... I will use the suggested approach below or your suggestion, thank you for your help...
– Morgs
2 days ago