Adjust website content depending on user's authentication status

My goal is to display a logout button when the user is logged in and a login button if they are not. I am using JSON tokens to determine if a user is logged in or not, by checking if the token is null. However, this approach does not seem to be working. Can anyone provide assistance?

home.page.ts

admin = false;

  constructor(private userService: UserService, private storage: Storage, private router: Router) {}


  ngOnInit() {
    this.router.navigateByUrl('home');
    if (this.storage.get('token') != null) {
        this.admin = true;
    } 
  }

home.page.html

 <ion-button *ngIf="admin==true">Logout</ion-button>
 <ion-button *ngIf="admin==false">Login</ion-button>

Answer №1

To update your code, make the following modifications:

  isAdmin = false;

  constructor(private userService: UserService, private storage: Storage, private router: Router) {}


  async ngOnInit() {
    this.router.navigateByUrl('dashboard');
    let token = await this.storage.get('token');
    if (!token) {
        this.isAdmin = false; //User is not authenticated
    } 
    else{
        this.isAdmin = true; //User is authenticated as admin
    }
  } 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AngularJS: Solving the issue of controllers not exchanging data by utilizing a service

I am working with the following controllers and service: angular.module('myApp', []); angular.module('myApp').factory('ShareService', function() { var information = {}; information.data = ""; information.setD ...

Angular2 application experiences exception in the karma test for checking karma

Is there a way for me to access more detailed logs? I'm struggling to pinpoint where the error is originating from. A critical error occurred while running my code: Chrome 57.0.2987 (Linux 0.0.0) ERROR Uncaught Response with status: 0 for URL: null ...

What strategies can be used to ensure that the page layout adjusts seamlessly to even the smallest shifts in window size?

Of course, I am familiar with media queries and how they allow us to set specific min-width and max-width ranges for CSS changes. However, when I look at the website styledotme.com, I notice that the block/div beneath the navigation bar gradually shrinks ...

Commit the incorrect file name with the first letter capitalized

There seems to be an issue with the git not recognizing the correct filename casing. I have a file named User.js in my workspace, but when checking the git status, it displays user.js instead. Despite repeatedly changing and committing as User.js, the gi ...

Dynamic options can now be accessed and modified using newly computed getters and setters

When using Vuex with Vue components, handling static fields that are editable is easily done through computed properties: computed: { text: { get() { return ... }, set(value) { this.$store.commit... }, }, }, <input type ...

JavaScript: create a collision detection algorithm to find pairs of objects in an object, not an array

I'm in the process of developing a Javascript game and I'm facing the challenge of implementing collision detection. Each element rendered in the game has its own unique ID and is stored in an object. I opted for using an object as a container i ...

Display the notification list by utilizing the "ToastController" function

Upon entering the home screen, I want to notify the user by displaying a list of messages from a firebase collection. The field to be displayed is "text", but I only want to show messages with the "read" field set as false. Once a message is shown, its "re ...

What could be the reason for the variable not resetting in my event handler?

Check out the code I've written below: $(document).ready(function () { var default_var = 2; var show_var = default_var; var total_var = 8; var increment_var = 2; var start_var = show_var+1; var end_var = show_var+increment_v ...

Learn how to effectively transfer data from $.getjson to PHP, specifically through the use of Laravel's @foreach loop

$.getJSON( 'http://localhost/media_books/index.php/new_books.json?provider_id=1&limit=99&offset=1') .done(function( json ) { $(tar).closest('.accordion').children('div').text(json); }); I have successfully obtaine ...

chart for visualizing two rows with matching IDs and dates

I have been attempting to accomplish the following two scenarios: 1) When both ID and dates are the same in the chart, but the descriptions differ, I want to display them on separate lines. 2) If there is not enough room to show the row label, I would li ...

I'm looking for the location of Angular Materials' CSS directives. Where can I find them?

Currently, I am using components from https://material.angularjs.org/latest/ for a searcher project. One specific component I am working with is the md-datepicker, and I would like to implement some custom styles on it such as changing the background colo ...

The positioning of the Material Ui popover is incorrect

I am currently working on a web application project with React and have implemented Material UI for the navbar. On mobile devices, there is a 'show more' icon on the right side. However, when I click on it, the popover opens on the left side disp ...

I am looking to split an array into smaller subarrays, each containing 5 elements, and assign a distinct class to the elements within each subarray. How can I

I have a group of "n" "li" elements that I would like to split into "x" subsets using jQuery. Each subset should contain 5 "li" elements, and I also want to assign a different class to each subset. <ul> <li>text1</li> <li>text2&l ...

Transform an array of strings into an array of object IDs

Recently, I encountered an issue with transforming an array of strings into object IDs using mongoose type. Unfortunately, my attempt was unsuccessful as it seems the method only works for single string inputs, not arrays. let stringObjectIdArray = [&apos ...

Inadequate execution of a Faux Router

UPDATE: After following the advice provided in the solution below, I realize that I confused router testing methods. I have made the necessary changes to my code and the tests are now passing, but I am encountering this warning: WARN LOG: 'Navigation ...

Utilizing NodeJS to initiate an http request and interact with a hyperlink

I am implementing website conversion testing and want to modify this code so that 10% of the http requests also click on a specific #link within the page. What additional code do I need to achieve this? var http = require('http'); http.createSer ...

Receiving feedback from an http.post request and transferring it to the component.ts file in an Angular

Currently, I am facing an issue with passing the response from an http.post call in my TypeScript service component to an Angular 2 component for display on the frontend. Below are the code structures of my service.ts and component.ts: getSearchProfileRes ...

How can I determine the size of the custom options dropdown in Magento?

I'm facing a challenging issue that I can't seem to crack. It might be because I'm still learning the ropes and struggling with technical jargon. Please bear with me as I try to explain my problem. Here is a summary of what I'm trying ...

Tips for executing a function in the HC-Sticky plugin?

Currently, I am utilizing the HC-Sticky JavaScript plugin and endeavoring to utilize the documented reinit method. However, I am facing difficulty in understanding how to execute it. In this CodePen demo, a basic setup is displayed along with an attempt t ...

Divide the identical elements and distinct elements from a provided array into two separate arrays storing unique elements and recurring elements

Can anyone help me with this query? I have an array of objects that need to be separated into repeating and non-repeating objects based on the segments they belong to, each in a separate array. For example- [ {name:"abc",id:1,segments:[1,2]}, {n ...