What is the proper method of exiting a subscription within a function in Angular?

Is the following method the correct way to return a value?

  private canView(permission: string, resource: string): boolean {
    let result: boolean;

    this.accessChecker.isGranted(permission, resource)
      .pipe(
        take(1)
      )
      .subscribe(
        granted => {
          result = granted;
        }
      );

    return result;
  }

This method is used to set the show property for a menu item:

    @Component({
      selector: 'ngx-pages',
      styleUrls: ['pages.component.scss'],
      template: `
        <ngx-one-column-layout>
          <nb-menu [items]="menu"></nb-menu>
          <router-outlet></router-outlet>
        </ngx-one-column-layout>
      `,
    })
    export class PagesComponent {
    menu: NbMenuItem[] = [
    {
      title: 'Admin area',
      icon: 'settings-outline',
      show: this.canView('view', 'it_only'),
      children: [
        {
          title: 'config.json',
          link: '/pages/admin-it/config-json',
        },
        {
          title: 'JWT',
          link: '/pages/admin-it/jwt',
        },
      ]
    }]

    constructor(private accessChecker: NbAccessChecker) { }

    private canView(permission: string, resource: string): boolean {
      // see above
    }

Is it possible for the result to be returned before its value is set in the subscription (since subscribe is asynchronous)? If so, what is the correct approach to take?

Answer â„–1

Are you utilizing this method to generate boolean values for various canView authorizations? If that's the case, you can simply convert those booleans into Observables.

canViewElement1$ = this.canView('element1', 'res1');
canViewElement2$ = this.canView('element2', 'res2');

private canView(permission: string, resource: string): Observable<boolean> {
    return this.accessChecker.isGranted(permission, resource);
}

When using this in the template for ngIf, use the async pipe. This way, you won't need to worry about unsubscribing or using take(1) like this:

<div *ngIf="canViewElement1$ | async">
...
</div>

Answer â„–2

The outcome may not reflect the current subscription value at that particular moment.

Answer â„–3

Consider transforming the function canView into an async function. You can achieve this by converting the Observable returned by the isGranted function to a promise using the toPromise() method, then use await to wait for the result

  private async canView(permission: string, resource: string): Promise<boolean> {
    let result: boolean = await this.accessChecker.isGranted(permission, resource)
      .pipe(
        take(1)
      ).toPromise();
    return result;
  }

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

Guide on creating a dash-patterned line over a rectangle using PixiJS and Angular

https://i.sstatic.net/uIksi.jpg In this example, we are creating a PixiJS application that draws a solid-stroked rectangle. Unfortunately, PIXI.Graphics does not have a built-in feature to draw dashed strokes. import { Component, OnInit } from &ap ...

Angular HttpClient mapping causes the removal of getters from the target object

Utilizing the HttpClient to fetch Json data from an API, I am utilizing the autoMapping feature of the HttpClient to map the json response to a specified object in this manner: this.httpClient.post<Person>(url, body, { headers: headers, params: http ...

Combine all TypeScript enums into a single one

Looking for a way to combine two separate enums into one for easier use. export enum ActionTypes1 { ClearError = 'CLEAR_ERROR', PrependError = 'PREPEND_ERROR', } export enum ActionTypes2 { IncrementCounter = 'INCREMENT_COUNT ...

Refreshed pages in Next.js often encounter intermittent 503 service unavailable errors with static chunks

Currently working on a static export website in next.js with the following configuration settings. Update: It appears that the 503 errors are related to nginx 503s when serving the files. I can provide the nginx configuration if necessary. const nextConfi ...

The ng test is not successful due to a SassError that indicates the stylesheet import cannot be found

I am facing an issue with my .scss files in my Angular project. Everything works fine when I build for development or production, but when I run tests using ng test, I encounter errors like: SassError: SassError: Can't find stylesheet to import. 1 â” ...

Tips for tracking the evolution of changes to an array within React State

Experiencing challenges with saving the history of updates and modifications on a State. I have an object called "Journey" which includes a list of workshops (another array). Whenever I update my list of workshops, I aim to create a new array that captures ...

Looking to retrieve the selected item from the list using console.log

Brief explanation: I am trying to retrieve the clicked item from a list using console.log(i.match). Please refer to my **home.html** code snippet below for how the list is dynamically generated. home.html <ion-card> <ion-card-content *ngFor="l ...

Can you conduct testing on Jest tests?

I am in the process of developing a tool that will evaluate various exercises, one of which involves unit-testing. In order to assess the quality of tests created by students, I need to ensure that they are effective. For example, if a student provides the ...

Angular 6 - Build a dynamic single page housing various applications within

I am faced with the task of developing multiple applications using Angular 6. Each application will have its own set of components, services, and more. However, there is also a need for shared services, components, directives, and other elements that will ...

Is it possible to transform a tuple type into a union?

Is it possible to map a tuple's generic type to a union type? type TupleToUnion<T> = T[keyof T]; // This will include all values in the tuple const value: TupleToUnion<[7, "string"]> = 2; // This assignment should not be permitted since ...

The Firebase Authentication Emulator consistently presents authentic Google account suggestions

TL;DR I am facing an issue with the Firebase Auth Emulator suggesting real Google accounts instead of dummy accounts. DETAILED Setting up firebase providers: importProvidersFrom( provideAuth(() => { const auth = getAuth(); if (en ...

I am deciding between using CommonJS or ES module for my sub packages in a Yarn workspace for my Next.js project. Which one

Currently working on a Next.js monorepo project using TypeScript and yarn workspace. Within the yarn workspace, there are two packages: /web and /api. The /web package is a next.js project, while /api serves as a shared subpackage utilized by /web. /my-pr ...

Using Material-UI with TypeScript

Attempting to integrate TypeScript/React with Material UI has been quite the challenge for me so far. Here is my index.tsx file: declare function require(p: string): any; var injectTapEventPlugin = require("react-tap-event-plugin"); injectTapEventPlugin( ...

Executing POST calls to a Google Apps Script

Everything was running smoothly. I managed to set up an endpoint using Google Apps Script that allowed end users to send a message to me (or another contact) and receive a copy of that message as well. The code for the POST request looked something like ...

Guide to utilizing Angular's translate i18n key as a dynamic parameter within HTML

Looking to pass an i18n translate service key as a parameter function on an HTML component. Attempted the following, but instead of getting the text, it's returning the key value. Created a variable assigned with the title in the component.ts file. ...

The resource in CosmosDB cannot be found

I have successfully stored documents on Cosmos, but I am encountering an issue when trying to retrieve them using the "read" method. this.cosmos = new CosmosClient({ endpoint: '' key: '' }); this.partitionKey = '/id' thi ...

Yes, it's not able to retrieve the value from headlessui combobox

I have encountered an issue while using the Headlessui combobox component in conjunction with Yup. Despite successfully storing the selected value in the selectedMemory state variable, Yup consistently generates a required error message. I seem to be overl ...

Issue encountered with Firebase JS SDK: firebase.d.ts file is missing which leads to a Typescript error when trying to

I'm currently working on an Ionic project with AngularFire. I encountered a typescript error when trying to run ionic cordova build --prod --release android. typescript error '/home/sebinbenjamin/workspace/myapp/node_modules/firebase/firebase. ...

Steps to access a Request object within a Controller

I am currently working with Express and Typescript, utilizing Controllers for managing requests. In an attempt to create a BaseController that includes the Request and Response objects for each request, I wrote the following code snippet. However, it see ...

How can you ensure a code snippet in JavaScript runs only a single time?

I have a scenario where I need to dynamically save my .env content from the AWS secrets manager, but I only want to do this once when the server starts. What would be the best approach for this situation? My project is utilizing TypeScript: getSecrets(&qu ...