Ways to correct the issue of null type in Angular

Within my Angular application, I make calls to multiple APIs depending on the user's role - whether they are a regular user, super user, or admin.

For each type of user, there is a designated dashboard that they should be directed to after login.

.service.ts:

public errors: any = [];
public  userProfile: any;
userType: any;

dataLog = {
     location : "lat: "+localStorage.getItem('lt')+",lng:"+localStorage.getItem('lt'),
     action : "Dashboard View",
     login_status: 1
}

//Upon logging in, I need to fetch user profile using the following API call:

public login(user) {
    this.http.post(environment.apiUrl+'/api/login', JSON.stringify(user), this.httpOptions).subscribe(
      data => {
        this.updateData(data['token']);
        localStorage.setItem('token',data['token']);
        
        var jsons=this.dashboardService.create('',this.token);
        this.userProfile();

let userProfile = JSON.parse(localStorage.getItem('profile'));
          let httpOptions = {
              headers: new HttpHeaders({
                'Content-Type': 'application/json',
                'Authorization': 'Token ' + this.token

              })
            };
            if(userProfile.usertype === 'Admin'){
          
               this.http.post(environment.apiUrl+'/api/activity/adminsession',JSON.stringify(this.dataLog), httpOptions).subscribe(
              (dataforlogin1)=>{
          console.log(dataforlogin1);
               },
              err=>{
                console.log("Error",err)
              }
            
            );
          }
           else if(userProfile.usertype === 'Super User'){
                this.http.post(environment.apiUrl+'/api/activity/superusersession',JSON.stringify(this.dataLog), httpOptions).subscribe(
                (dataforlogin2)=>{
            console.log(dataforlogin2);
                 
                },
                err=>{
                  console.log("Error",err)
                }
              );
          
            }
            else{
               this.http.post(environment.apiUrl+'/api/activity/usersession',JSON.stringify(this.dataLog), httpOptions).subscribe(
                (dataforlogin3)=>{
            console.log(dataforlogin3);
                 
                },
                err=>{
                  console.log("Error",err)
                }
              
              );
            }
          },

 userProfile() {
              let httpOptions = {
                headers: new HttpHeaders({
                  'Content-Type': 'application/json',
                  'Authorization': 'Token ' + localStorage.getItem('token')
                })
              };
              this.http.get(environment.apiUrl+'/profile', httpOptions).subscribe(
                (profile:any)=>{
            
                 localStorage.setItem("profile",JSON.stringify(profile));
                 console.log("profile:",JSON.parse(localStorage.getItem("profile")))
                 
            
                 if(profile.usertype==="Admin"){
                   
                  this.router.navigate(['/admin']);
              
              }
              else if(profile.usertype==="Super User"){
              this.router.navigate(['/superuser']);
              }
              else{
              this.router.navigate(['/dashboard']);
              }
                },
                err=>{
                  console.log("Error",err)
                }
              );
              }

The functionality works as expected. However, upon removing the localStorage information through developer tools, the dashboard data does not display and an error message appears:

Cannot read property 'usertype' of null
at SafeSubscriber.http.post.subscribe.errors

I would appreciate any assistance in resolving this issue.

Answer №1

By utilizing the code snippet below, you can easily navigate into the else if statement when userProf is null

if(userprof.usertype && userprof.usertype === 'Admin'){
          
               this.http.post(environment.apiUrl+'/api/activity/adminsession',JSON.stringify(this.datalog), httpOptions).subscribe(
              (dataforlogin1)=>{
          console.log(dataforlogin1);
               },
              err=>{
                console.log("Error",err)
              }
            
            );
          }
           else if(userprof.usertype && userprof.usertype === 'Super User'){
                this.http.post(environment.apiUrl+'/api/activity/superusersession',JSON.stringify(this.datalog), httpOptions).subscribe(
                (dataforlogin2)=>{
            console.log(dataforlogin2);
                 
                },
                err=>{
                  console.log("Error",err)
                }
              );
          
            }

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

Angular 6: Issue with displaying data on the user interface

Hello! I am attempting to fetch and display a single data entry by ID from an API. Here is the current setup: API GET Method: app.get('/movies/:id', (req, res) => { const id = req.params.id; request('https://api.themoviedb.org/ ...

Controlling a generic interface's acceptance of certain data types in typescript: a guide

Is there a way to restrict a generic interface from accepting specific data types in TypeScript? I understand that I can define acceptable data types for a generic interface in TypeScript. interface exampleInterface<T = void | any>; But what if I w ...

Angular 5 in conjunction with Keycloak enabling access for non-authenticated users

I have a situation where I need to implement anonymous user access in my app, and for that purpose, I am incorporating the 'keycloak-angular' library along with Angular 5. The documentation instructs me to initialize the application as shown belo ...

Ways to stop dropdown from closing when choosing a date in mat datepicker

Utilizing both Bootstrap dropdown and mat date picker in a drop-down menu presents an issue wherein selecting a date from the mat date picker results in the closure of the dropdown. Preserving the dropdown's visibility post-selecting the date is desir ...

I am facing conflicts between vue-tsc and volar due to version discrepancies. How can I resolve this problem?

My vsCode is alerting me about an issue: ❗ The Vue Language Features (Volar) plugin is using version 1.0.9, while the workspace has vue-tsc version 0.39.5. This discrepancy may result in different type checking behavior. vue-tsc: /home/tomas/Desktop/tes ...

Is it recommended to ensure all of my components are nested within the root App component?

As I delve into learning Angular 4 with angular-cli for creating a web front end, I can't help but wonder about the structure of my components. In following the Heroes tutorial and applying it to my own data models, I noticed that all my components, ...

"Hello, I attempted to establish communication between components using services in Angular 2, but I am encountering an issue where the

The second part of this page requires fetching values from the first component. import { Component } from '@angular/core'; import {AppService} from './app.service'; import { Http,Response } from '@angular/http'; ...

Form a collection using multiple elements

I'm attempting to combine multiple arrays into a single array. For instance : array1= ['Joe','James','Carl','Angel','Jimmy',]; array2= ['22','11','29','43',&apo ...

Convert an array of strings to my custom array type in Angular

I have a list of different statuses Here is an example of it: export enum InvoiceStatus { Created = 1, Pending = 2, Approved = 3, Rejected = 4, Paid = 5, Deleted = 6, PreparingPayment = 7 } My goal is to convert it into an ar ...

.NET and Angular Collaboration

Currently, I'm embarking on a new adventure of creating a .NET and Angular project from the ground up. In order to kickstart the process, I decided to utilize the "ASP.NET Core Web API" template within Visual Studio and also employed npm run ng new Cl ...

Importing a CSS file into your Angular project's index.html file

I am currently facing a challenge while trying to utilize the angular2-busy library within an Angular project that was generated using the CLI. The issue arises when attempting to import the stylesheet: <link rel="stylesheet" href="/node ...

React, Typescript, and Material-UI 4 compilation dilemma

Out of the blue, my entire project collapsed and I can't seem to build it. I recently reset the project using a fresh create-react app build, which seemed fine initially. However, just yesterday, I encountered a similar issue but with a different erro ...

Encountering issues with Angular2 forms while working with JavaScriptServices/Universal

My Angular2 app was built using the JavaScriptServices starter from GitHub. The issue I'm encountering is a runtime error when I include a form in a component. Both FormsModule and ReactiveFormsModule are being imported. This is how my form is stru ...

Utilizing Router Outlet in Angular to Access API Data

I've encountered an issue where I can't pass parent data from the ngOnInit route params to my child component, user-seminar. After some research and searching on Google, I found a solution involving services. To address this problem, I modified ...

Making Angular table cells interactive with clicks

My table consists of multiple rows, and I want to change the color of a cell to red when clicked. However, only one cell should be red at a time. Whenever I click on a new cell, the previously red cell should return to its original color. How can I achieve ...

Angular 4 not refreshing the view

I have encountered an issue where I am setting an array value in one component inside a subscribe method and then getting the values of that array in another component. After receiving the values, I set a flag in the component where I obtained the array va ...

Modifying CSS styles dynamically in Angular2 poses a challenge

I am utilizing angular2 to design a few input forms. They are disabled when the user lacks permission to modify them, but upon an admin login, the inputs become enabled. In order to enhance visibility, I attempted to style them with gray when disabled and ...

Utilize a variable from one Angular component in another by sharing it between .ts files

My issue involves dynamically adding items to a todo list and wanting to exclude certain items. The challenge lies in the fact that the list itself is located outside of the task component: Within the task.component.html file, I iterate through the list f ...

Encountering "Unknownhostexception" error while executing API test cases on Jenkins

Encountering an unknown host exception when running API test cases in Jenkins, despite it working fine locally. Upon debugging on the Jenkins slave machine, it seems to be a configuration issue, but the exact root cause is uncertain. java.net.UnknownHostEx ...

What is the best way to input variables specified in script setup for conducting unit tests?

In my component, I am utilizing a reactive state that is defined within the script setup section: const state = reactive({ hello: 'world' }) This state can be accessed in tests in this manner: wrapper.vm.state.hello = 'mad-world' ...