Reputation: 388
I want to use *ngIf in my angular project. I use app.component.html to handle login page and as well as dashboard. So I want to hide dashboard before user login to the website. After user logged to the system I want to show the dashboard.
So I use *ngIf to handle this. I use following code to handle the case.
In my app.component.html I use following div to show when ever user is not log to the system.
<div class="login-page" *ngIf="!isLog()">
... go some code here...
</div>
And following div is use to show the dashboard after user is log to the system.
<div class="main-dashboard" *ngIf="isLog()">
... go some code here and router outlet as well ...
<router-outlet></router-outlet>
</div>
Finally in my app.component.ts file is use isLog() method to check whether user is logged or not.
isLog(){
// Use to back end api to check user log
var log : boolean = false;
// If User is Log
// Use back end api to handle this
log = true;
return log;
}
But the issue is when user try to log to the system for first time this code structure works fine for that case. But after user log to the system if user refresh the page for little time (0.5 ms > time) system shows the login page and suddenly shows the current page.
I think this is because every time user refresh the page website try to check user is log. During that time isLog() method return false so website shows login page for that time.
After isLog() return the valid value it means true. Then it shows the dashboard.
But I want to avoid this case. After user log to the system I don't want to show login page even for little time. Because user get confused.
How can avoid this case? Is there are any possible way to handle this type of issue?? OR recommended way???
Upvotes: 2
Views: 922
Reputation: 2165
Of course it depends on your needs but the best practise is making the login page a seperate component and use Route Guards to protect the routes.
If having it in the same page and using ngIf is enough for your requirements which means you have a small application and it is not likely to expand, it is fine. The problem you experience is well explained by @Shashank Vivek in his answer.
Upvotes: 2
Reputation: 17504
If that's the case, try to store this info in sessionStorage which will persist the data for that tab and you wont have to wait for server response.
Also, as a side note, using *ngIf="isLog()"
is not a good approach. You can try to put console.log
in isLog()
and you'll see it getting triggered periodically. That's because of change Detection
cycle of angular which works on all the expressions assigned to template
, and since *ngIf
has function associated to it, that function (isLog()
) is executed.
Its better if you can evaluate this value on ngOnInit
and assign it some variable which will be used as a flag to check *ngIf
condition
Upvotes: 3