Pause for Progress - Angular 6

I'm looking for a solution to solve the following issue. I need to access a property that will store data from an http request. Therefore, I want to verify this property only after the transaction is completed.

  validateAuthorization(path: string): boolean{
    const currentUser: UserStorage = this.storage.getCurrentUser();
    let user: User
    this.userService.findUserByLogin(currentUser.login).subscribe(
        data => {
            user = data
        }

    )

    if (user.profile.springSecurity == 'ROLE_ADMIN'){
        return true;
    } else {
        const message: Message = {message: 'User does not have permission', type: MessageType.ERROR}
        this.message.notify(message)
        return false;

    }
}

Answer №1

To implement the necessary changes, you must update the function to return an observable instead. Utilize the map method to convert the data into the desired boolean outcome.

checkAuthorization(path: string): Observable<boolean>{
    const loggedInUser: UsrStoraged = this.storage.getLoggedInUser();
    return this.userService.findByLogin(loggedInUser.login).pipe(map(
        data => {
            const user = data

            if (user.profile.springSecurity == 'ROLE_ADMIN'){
                return true;
            } else {
                const message: Message = {message: 'User does not have permission', type: MessageType.ERROR}
                this.message.notify(message)
                return false;
            }
        }
    ))
}

If you haven't already done so, remember to import the necessary modules:

import {Observable} from "rxjs"
import {map} from "rxjs/operators"

Next, ensure that any code calling this function subscribes to the result. For instance, instead of:

if (checkAuthorization("foo")) {
    // do stuff
} else {
    // do other stuff
}

You should use:

checkAuthorization("foo").subscribe(isAuthorized => {
    if (isAuthorized) {
        // do stuff
    } else {
        // do other stuff
    }
})

Answer №2

data => { will be triggered upon receiving it, allowing you to encapsulate your code within:

checkAuthorization(path: string): boolean{
    const usuarioLogado: UsrStoraged = this.storage.getUsuarioLogado();
    let usuario: Usuario
    this.usuarioService.findByLogin(usuarioLogado.login).subscribe(
        data => {
            usuario = data
            if (usuario.perfil.springSecurity == 'ROLE_ADMIN'){
                return true;
            } else {
                const message: Message = {message: 'Usuário sem permissão', type: TipoMensagem.ERROR}
                this.message.notify(message)
                return false;

            }
        } 
    );
}

Tip: To handle errors, include error => {} similar to the structure of data mentioned above.

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

Methods to validate CSS attributes specified within a class using React testing library

I am struggling to validate the CSS properties defined within a class in CSS using the React Testing Library. Unfortunately, I am facing challenges in doing so. Here are the simplified code snippets: import React from "react"; import { render, ...

Issues with using hooks in a remote module in Webpack 5 module federation

I am attempting to create a dynamic system at runtime using Module Federation, a feature in webpack 5. Everything seems to be working well, but I encounter a multitude of 'invalid rule of hooks' errors when I add hooks to the 'producer' ...

When you want to place an image in the middle of a cell, you can easily achieve this by utilizing the addImage function

I am currently utilizing the addImage() method within the exceljs library to insert an image into a cell of an Excel file that is exported from my Angular application. While I have successfully added the image using the addImage() method, it appears in t ...

Craft dynamic SVG components using TypeScript

Looking to generate a correctly formatted SVG element using TypeScript: createSVGElement(tag) { return document.createElementNS("http://www.w3.org/2000/svg", tag); } Encountering an issue with tslint: Error message: 'Forbidden http url in str ...

The production build encountered an issue as it was anticipating 3 arguments, however, it only received

import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'elipsis' }) export class ElipsisPipe implements PipeTransform { transform(text, length, clamp) { text = text || ''; clamp = clamp || '...& ...

evaluate a utility function that operates on children

In managing a component that requires children (referred to as the layout component), there is a specific function nested within this component that processes these child components. Testing this function poses a challenge, so I decided to extract it into ...

Angular CDKScrollable not triggering events

I'm having trouble making the angular CdkScrollable work when creating my own div: <div class="main-section" id="mainsection" #mainsection CdkScrollable> <div class="content" style="height: 300px; backgr ...

Using Angular, a function can be called recursively directly from within the HTML

I'm struggling with loading an image because the method getUserProfileImage() is getting triggered multiple times within a loop. Is there a way to ensure the method is only called once during each iteration? I understand that this issue is related to ...

Experiencing template parsing errors in Angular 2+ unit tests with Karma and Jasmine

Encountering problems with running Angular tests on certain components, even though they function properly in production. Seeing the following error message: Failed: Template parse errors: 'app-date-picker' is not a recognized element: 1. Ensure ...

Webpack is throwing an error: TypeError - It seems like the object prototype can only be an object or null, not

My Angular 4 application is utilizing webpack. Strangely, I encounter an error when attempting to run it on my Amazon server, although it works perfectly fine on my local machine. Any insights into why this might be occurring? Thank you very much for any ...

ngx-translate is failing to display any text within a lazily-loaded module

We are currently utilizing Angular 6 within our application and have recently initiated the process of preparing our app for lazy-loading. Our application consists of multiple lazy-loaded routes, and our goal is to utilize a single language file for all ro ...

What is the process for including an item in an array within Firestore?

Can someone help me with this code snippet I'm working on: await firebase.firestore().doc(`documents/${documentData.id}`).update({ predictionHistory: firebase.firestore.FieldValue.arrayUnion(...[predictions]) }); The predictions variable is an ar ...

Angular Observable does not reflect updates automatically

I have a unique service that I utilize to pass on a particular value so that it is easily accessible to all components requiring it: setAnalysisStatus(statuses: AsyncAnalysis[]) { this.analysisStatus.next(statuses); } In ...

Steps for storing API information in localStorage:1. Retrieve the API data

My app is running sluggish due to the excessive API calls for information retrieval. To optimize performance, I want to create a unified object containing all the data that can be shared across pages and accessed from localStorage, thus enhancing the app ...

Can a custom structural directive be utilized under certain circumstances within Angular?

Presently, I am working with a unique custom structural directive that looks like this: <div *someDirective>. This specific directive displays a div only when certain conditions are met. However, I am faced with the challenge of implementing condit ...

Angular2 - adding the authentication token to request headers

Within my Angular 2 application, I am faced with the task of authenticating every request by including a token in the header. A service has been set up to handle the creation of request headers and insertion of the token. The dilemma arises from the fact t ...

How to set the default theme color for the mat-sidenav background in Angular 6 and 7?

Is there a way to make the background of a mat-sidenav match the theme color of my mat-toolbar? In the file src\styles.scss, I have the following: @import '~@angular/material/prebuilt-themes/indigo-pink.css'; The template / HTML file incl ...

Data fetched using React Query

When using React Query to fetch data, the function runs smoothly. After console.logging the 'data' variable from React Query, it prints an array of objects as expected and handles states efficiently between loading, success, error. The issue ar ...

Angular 2+ encountering an internal server error (500) while executing an http.post request

Here is my service function: public postDetails(Details): Observable<any> { let cpHeaders = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: cpHeaders }); return this.htt ...

Angular 16 HttpClient post request with asynchronous action

Here I am working on integrating JWT in Angular with a .Net Core API. When I start my Angular server and launch the application, I encounter the following scenarios: Attempting with correct credentials initially fails, but retrying allows it to work. Tryi ...