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

How come the props aren't being passed from the parent to the child component? (React / TypeScript)

Learning TypeScript for the first time and facing an issue with passing props from parent to child components. The error seems to be related to the type of props, but I'm not sure how to fix it since all types seem correct. Error message: "Property ...

What is the best way to extract a variable from a URL and assign it to an Ionic variable

I am currently developing a project in Ionic 3 that utilizes the admob plugin. I have set up two variables (Mybanner and Myinterstital) to store the admob code, and I would like to retrieve the content of these variables from an external URL like this: ht ...

Oops! Issue encountered while trying to read the file "src/core/database/config.ts"

Need help with migrating a database in a Node Nest.JS application. When running the npx sequelize-cli db:migrate shell command, I encountered the following exception: Error details: Error: TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".t ...

Developing a function that takes a parameter which can be used with or without an additional argument when invoked

In my React application, I have a method that accepts a parameter for displaying a modal. const displayModal = (p:Result) => { setConfirm(true); if(p) { //check variable for truthy setSelectedRow(p); } ...

The number of keys in the related object must correspond to the length of the array in Advanced Generic Types

Can we achieve type safety across rows and columns by having one object define the structure of another? Starting Point: export interface TableColumn { name: string; type: "string" | "number" | "action"; id: string; } ...

Eliminate the need for require statements in TypeScript-generated JavaScript files

I am working on a website project and utilizing TypeScript for development. While using the tsc compiler, I noticed that all my JavaScript code compiles correctly. However, when I include an import statement in my TypeScript files, it gets compiled into J ...

Making sure the checkbox stays selected in an angular environment

After experimenting with Angular 9 and a custom input, I achieved the following result => https://stackblitz.com/edit/angular-ivy-rgsatp My goal was to prevent users from disabling a radio button that is currently checked. Therefore, I made changes in ...

Angular routing is giving me trouble when trying to open various menus at the same location

I am new to Angular and facing a situation where my HomeComponent has a reference to the Appmenucomponent in its .html page. I need to be able to click on different menus (each leading to a new component) and have them open in the same place (div), similar ...

Utilizing the '+' symbol in path for efficient Express routing

Currently, I am utilizing Express to manage the hosting of my Angular2 application on Azure cloud services. In accordance with the Angular2 style guide, I have designated certain components as lazy loaded by adding a '+' prefix to their folder n ...

Angular2 bootstrapping of multiple components

My query pertains to the following issue raised on Stack Overflow: Error when bootstrapping multiple angular2 modules In my index.html, I have included the code snippet below: <app-header>Loading header...</app-header> <app-root>L ...

Setting up TypeScript compilation for TS modules in an AngularJs application: A comprehensive guide

After conducting a test, it has come to my attention that TypeScript 2.6.2 imposes a requirement where imported elements need to be used in a new before the module is referenced in a require. The test is based on the following code snippets extracted from ...

Angular: Template parsing errors: Parser Error: Unexpected token "=" at column

I've been working on an Angular app created with Angular CLI and encountered unexpected token errors with the new template parser. The error messages from Angular look like this: **ERROR in Template parse errors**: Parser Error: Unexpected token ) a ...

Sending an image in the body of an HTTP request using Angular 7

I'm currently in the process of developing an Angular application that captures an image from a webcam every second and sends it to a REST API endpoint for analysis. To achieve this, I have implemented an interval observable that captures video from t ...

Clearing transformation offset in Angular Material Drag and Drop

In my web application, I am working with a <div> element that has the CSS property position: absolute, placed inside a container with position: relative. The left and top properties of this element are linked to data X and Y in the backend component. ...

Guide to navigating to a specific module within an Angular 2 application directly from the index page

As a newcomer to angular2, I recently obtained a sample login and registration code online. However, when I run the code, it displays the index page instead of the "login" module located within the app folder. Can someone please advise me on how to redire ...

Tips for enabling TypeScript's static typings to function during runtime

function multiply(num: number): number { console.log(num * 10) // NaN return num * 10 } multiply("not-a-number") // result == NaN When attempting to call the function above with a hardcoded invalid argument type, TypeScript correctly identifies and w ...

Error: The NgTools_InternalApi_NG_2 member is not exported in compiler-cli/src/ngtools_api

Currently, my ng serve command is not working and showing the following error message: ERROR in node_modules/@angular/compiler-cli/index.d.ts(20,10): error TS2305: Module '"./node_modules/@angular/compiler-cli/src/ngtools_api"' has no expor ...

Real-time data not instantly stored using socket.io

In my current issue, whenever I receive a message with the action stop, I encounter a problem specifically with the setTotalScore function. Initially, the totalScore is set to 0, and upon receiving the message, it should update to match the user.score. How ...

Updating object properties in Typescript

I have written the following Angular 2 TypeScript code: import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) ...

Converting an image file from the local directory to base64 encoding in an Angular application

Can someone help me convert a locally stored image named xyz.JPEG from the folder assets/img to base64 in Angular 8? I have attempted using FileReader and btoa, but it has not been successful. var reader = new FileReader(); var binaryString = reader.rea ...