Update the disabled state following the onInit event

Currently, I am developing an angular application at my workplace that requires implementing permissions. The backend stores permissions as either 1 or 0, and the frontend queries a service to retrieve the user's permission. If the user lacks permission for a specific action, the corresponding button is disabled. After careful consideration, we concluded that the most effective solution would be to save the permission to session storage on application startup and retrieve it from there whenever necessary.

This approach works flawlessly once the application launches. Every page successfully reads the permission and disables the appropriate buttons. However, I encountered an issue during the initial launch of the application. Since the permission retrieval is an asynchronous process, the application continues to start up while waiting for the permission to be fetched. As the default permission is set to none, the first page displays a disabled button even after obtaining the permission due to being created before the asynchronous call. A manual refresh resolves this issue.

I have been exploring ways to either detect changes in session storage and update the initial component accordingly or ensure that the application waits for the permission retrieval process to complete before continuing the startup sequence. Any guidance on this matter would be greatly appreciated.

-Thank you

Answer №1

You can give this a try, it has worked well for me:

First, create a service named BroadCasterService -

import { Injectable } from '@angular/core';
import { Subject, Observable, BehaviorSubject } from 'rxjs';
import { filter, map } from 'rxjs/operators';

export class BroadcasterModel {
key: string=''
data: any;
}
@Injectable({
providedIn: 'root'
})
export class BroadCasterService {
public title = new BehaviorSubject('');
private subject = new Subject<BroadcasterModel>();
public sideNavToggleSubject: BehaviorSubject<any> = new 
BehaviorSubject(null);
broadcast(key:string, data:any) {
    this.subject.next({ key: key, data: data });
}
on(key:string): Observable<any> {
    return this.subject.pipe(filter(m => m.key == key), map(m => 
m.data));
}
setTitle(title: string) {
    this.title.next(title);
}
public toggle(data:any) {
    return this.sideNavToggleSubject.next(data);
  } 
}

Next, import this service into your component where you need to set session data -

import { BroadCasterService } from '../services/broad-caster.service';

Include the service in your constructor -

 constructor(private broadcastService: BroadCasterService)

Along with setting the session data, also set the permission data in the broadcast function -

this.sharedService.getPermission('').subscribe((res: any) => {
  this.storage.setLocalStorageData('permissionData', res?.data, true);
  this.broadcastService.broadcast("permissionData", res?.data);
});

Use the broadcast service to handle permissions -

let modules :any;
 modules = localStorage.getItem("permissionData");
 this.broadcastService.on('permissionData').subscribe(cic => {
        modules = cic; //this keeps the data until the page is refreshed
 });

After refreshing the page, you can retrieve the permission data from session storage.

I believe this solution will be beneficial for you.

Answer №2

Hey there! I've put together a sample process-diagram for you: Check out this diagram

https://i.sstatic.net/ENHPz.png

You have a few options for implementing something similar:

  1. Utilizing HttpInterceptors + UI-Spinner for all backend requests. Tutorials: Angular show spinner for every HTTP request with very less code changes Implementing global loaders using HttpInterceptors
  2. Developing a custom solution specific to this case (without HttpInterceptor)
  3. Incorporating resolvers

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

Upon successfully logging into the app, Azure AD B2C integrated with MSAL and Angular will automatically redirect users to the login page

I recently updated my Angular app to make it accessible to customers by switching from ADAL to MSAL for authentication. I configured the app with Azure AD B2C credentials and everything seems to be working smoothly, except for one issue. When I try to logi ...

The issue with the Angular 5 HttpClient GET-Request not closing persists

Currently, I am utilizing an Http-GET request to fetch JSON data from my backend service. Service: public storedCategories: BehaviorSubject<Category[]> = new BehaviorSubject(null); constructor() { const subscription = this.http.get&l ...

The Angular Material Table Collapse feature offers dynamic collapsing similar to jQuery Datatable

Is there a way to improve the appearance of my Angular Material Table, especially on mobile? https://i.stack.imgur.com/sZXPP.png The current display of my Angular Material Table is not aesthetically pleasing when viewed on mobile devices. https://i.stack ...

What is the process for converting/executing TypeScript into JavaScript?

Having trouble running https://github.com/airgram/airgram Encountering this warning message from the post (node:9374) Warning: To load an ES module, set "type": "module" Have already added {"type": "module"} To pa ...

Troubleshooting Angular4 and TypeScript Compile Error TS2453: A Comprehensive

I'm facing an issue in my Angular4 project build process which I find quite perplexing. The error seems to be related to the import of certain components such as Response, Headers, and Http from @angular. Whenever I attempt to build my project, it thr ...

How can one determine the source of change detection activation in Angular 2?

I just launched a new component and it appears to be causing change detection to occur multiple times per second: // debugging code ngDoCheck() { console.log('DO_CHECK', new Date().toLocaleTimeString()); } Results: https://i.sstatic. ...

How can I use Laravel to enter data using the post method?

I've been struggling with data transfer in my Angular component for a while now, specifically using a post method. Despite extensive research and reading various documents, I haven't been able to find a solution. Can you assist me with this issue ...

Retrieving the ng-content from an ng-template within one component and passing it to another component

Although there are various approaches available, my preference is to utilize ng-template, ng-content, and the @ContentChild() decorator in a specific way inspired by the implementation of Angular Material components. In this scenario, I have defined two c ...

Angular 7 routing glitches causing page refresh issues

Here is the issue I'm facing: I am looking for a way to switch between tabs in my navigation bar without having to refresh the entire website. I have just started working with Angular and I believe that the router should be able to route to a new pag ...

Setting up Template-driven Form in Angular 7

I am searching for a solution to pre-populate specific form fields and then execute a function containing an if(this.form.valid) condition. Within the ngOnInit method, there is an API request that retrieves basic information and populates it within the fo ...

Choosing a particular checkbox with changing identifiers in Cypress: A guide

Having trouble selecting a specific checkbox without a distinct identifier? The ID keeps changing, so using it to target the checkbox directly isn't an option. Check out this image of the checkbox: https://i.stack.imgur.com/kwzAS.png This particular ...

How to pass parameters from a directive to a child component in Angular

I am currently attempting to create a child component that can pass parameters using a directive, but I have not been able to find any tutorials on how to achieve this yet. I have tried looking at some resources, such as this one on Stack Overflow: Get re ...

Learn the process of uploading files with the combination of Angular 2+, Express, and Node.js

Need help with uploading an image using Angular 4, Node, and Express with the Multer library. Check out my route.js file below: const storage = multer.diskStorage({ destination: function(req, file, cb) { cb(null, 'uploads') }, filename: fun ...

What in the world is going on with this Typescript Mapped type without a right-hand side?

I encountered a situation where my React component had numerous methods for toggling boolean state properties. Since these functions all did the same thing, I wanted to streamline the process by creating a common function for toggling properties. Each met ...

What is the method for activating a button when a user inputs the correct email address or a 10-digit mobile number

How can I enable a button when the user enters a correct email or a 10-digit mobile number? Here is my code: https://stackblitz.com/edit/angular-p5knn6?file=src%2Findex.html <div class="login_div"> <form action=""> <input type="text" ...

Tips on accessing validator errors in Angular

Is there a way to extract the value from the 'minLength' validator error in order to use it in a message? This is my current HTML setup: <div class="mt-2" *ngIf="ngControl.control.errors?.minlength"> {{ &ap ...

Combine the selected values of two dropdowns and display the result in an input field using Angular

I am working on a component that consists of 2 dropdowns. Below is the HTML code snippet for this component: <div class="form-group"> <label>{{l("RoomType")}}</label> <p-dropdown [disabled] = "!roomTypes.length" [options]= ...

Angular 2, Release Candidate 5 - Dropdown form includes mysterious "phantom" choice

While working with Angular 2, RC 5, I have encountered a strange issue while building a form to create a new model object. The problem arises when there is an extra blank <option> appearing in the dropdown list after transpiling the code, even though ...

What is the best way to transform RestApi object information into an Array?

How can I transform the data fetched from PokeApi into an Array that can be used in Angular? When trying to assign it to an Array directly in HTML, it gives an error due to its Object return type. getPokemonDetail(index) { return this.http.get(`${this ...

Filter an array in Angular 2 and add additional data to it

Quick query: I have 2 arrays/objects. The first one contains all items, while the second contains selected IDs from the first array. My question is, what is the most efficient way to iterate through both arrays, identify selected items from the second arr ...