Looking to execute a service method within an authguard service?

I am a beginner with Angular and I am looking to invoke a service method within the authguard service. The specific service function that I need is as follows. Please note that I do not want to make any changes to this service function.

loadOrganizations() {
    this.getOrganizations().subscribe(
      (results) => {
        const organizationList = [];
        if (results.organizations) {
          results.organizations.forEach((element) => {
            this.appendOrganization(element, organizationList);
            this.loadChildrenOrganization(element.children, organizationList);
          });
        }
        this.organizations$.next(organizationList);
        this.organizations$.complete();
      },
      (error) => {
        this.organizations$.next([]);
        this.organizations$.complete();
      }
    );
  }

The calling method in my authguard TypeScript file is shown below.

canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Promise<boolean> {
 
     this.appService.loadOrganizations().then((answer: boolean) => {
          return answer;
      });
  }

I encountered a return type error with "Promise" and "then". Any suggestions on how I can properly call this service method within the authguard service?

Answer №1

Appreciate the help. The issue has been successfully fixed through

canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
     this.authService.checkUserAuthentication();
     console.log("auth guard executing")
     return true;
  }

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

Loading the Angular 2 library with the help of SystemJS

I recently went through the Angular2 quickstart guide on angular.io and came across their use of systemJs for app loading. Instead of importing, they load angular2, rx.js, and angular2.dev.js via script references. Is there a way to import these scripts? ...

MongooseError: Timeout occurred after 10000ms while attempting to buffer the operation `users.findOne()` in a Next.js application

Encountering the "MongooseError: Operation users.findOne() Buffering Timed Out After 10000ms" error in my Next.js app while using Mongoose (^8.2.2) to connect to MongoDB. Using Next.js version 14+ Troubleshooting Steps: 1. Checked MongoDB connection str ...

Attempting to install angular-in-memory-web-api using npm, but encountering various errors in the process

When trying to install angular-in-memory-web-api using npm, an error with code ERESOLVE occurred. The dependency tree could not be resolved, causing a conflict. While resolving dependencies for the project, it was found that @angular/common version ~13. ...

Confirm the Keycloak token by checking it against two separate URLs

In my system, I have a setup based on Docker compose with back-end and front-end components. The back-end is developed using Python Flask and runs in multiple docker containers, while the front-end is coded in TypeScript with Angular. Communication between ...

Believed I had a clear understanding of the situation

Within the following code snippet, I am utilizing a service (Angular) to extract text using a fileReader and implementing a promise for the asynchronous part. However, I am encountering an issue that appears to be related to scope, which is causing confusi ...

Using @Input to pass data from a parent component to a

Looking to modularize the form code into a separate component for reusability? Consider using @Input and referencing it in the HTML to pass values to the post method. Here's how you can achieve this: Previously, everything worked smoothly when all th ...

Steps for importing jQuery typings into TypeScript:1. First, install the jQuery

I've searched for similar questions, but haven't found one that matches my issue. Can someone help me figure out what to do next? In my Visual Studio project, I used package.json to download jquery typings into the node_modules folder: { "ver ...

Unable to access due to CORS policy restriction in Ionic 5 Angular platform

Encountering an error, seeking guidance on the issue. Configuration has been done in proxy.conf.json. Headers with base url have been set in user.service.ts. import { Injectable } from '@angular/core'; import { Http, Headers, RequestOptions } fr ...

The npm run scripts seem to be malfunctioning, but when the scripts are executed individually,

I've encountered an issue while attempting to execute scripts with NPM. Despite my efforts, I consistently end up with errors. Package.json "scripts": { "ng": "ng", "start": "ng serve --open", ...

Is it possible for me to create an interface that enables me to invoke a custom method on particular strings?

My database returns objects structured like this: interface Bicycle { id: string; created_at: string; } The data in the created_at field is a machine-friendly date that I need to convert into a Date object for localization: new Date(bike.created_at). ...

Exploring the functionality of typeahead with server-side data integration

I am utilizing ng-select with Angular 7 and creating the following component: export class PostComponent { selectedCategoryID: number; allCategories$: Observable<CategoryModel[]>; constructor(private catService: CategoryService) { } ngOn ...

Issue with typing error in datetime.d.ts file that is missing

I initially installed the typings for luxon using npm install --save-dev @types/luxon. However, upon further evaluation, I realized that it was unnecessary and decided to remove it manually: deleted the folder node_modules/@types/luxon removed entries in ...

Using Generic Types in TypeScript Files for React Components

I have encountered an issue that I haven't been able to find a solution for online. When I define a function in a ts file like this: const lastGeneric = <T>(arr: Array<T>): T => { return arr[arr.length - 1]; } But when I try to do ...

An effective method for excluding null values with an Angular pipe

I am currently working on an Angular pipe that filters results based on user input. The problem I'm encountering is that some of the results do not have a value, resulting in this error message: Cannot read property 'toLocaleLowerCase' o ...

Downcasting on "this" is not supported in Typescript

In the example below, the TypeScript compiler does not allow for a direct cast of this to Child. However, it is possible to achieve this using an intermediate variable like 'temp' or double casting as shown in the commented lines. Is this behavio ...

Enhancing Web Service Calls with Angular 2 - The Power of Chaining

I am currently facing an issue where I need to make multiple web service calls in a sequence, but the problem is that the second call is being made before the .subscribe function of the first call executes. This is causing delays in setting the value of th ...

Angular Form Template Unidirectional Data Binding Example

I'm facing a challenge with one-way binding to a default value in my HTML form. Within my component, I have a Connection string that is initially set from local storage: export class AuthAdminComponent implements OnInit { public authenticated = f ...

Angular data binding with [object object]

Upon receiving data from my API, the console displays the following structure: [ { id:"123", name:"asd", address:"st.dddss", status:1 } ] After attempting to iterate through it using ngFor, an error is thrown: E ...

This error message in AngularJS indicates that the argument 'fn' is not being recognized as a function

I am currently working with angularjs and typescript and I am attempting to create a directive in the following manner: Below is my controller : export const test1 = { template: require('./app.html'), controller($scope, $http) { ...

What is the proper way to utilize the router next function for optimal performance

I want to keep it on the same line, but it keeps giving me errors. Is there a way to prevent it from breaking onto a new line? const router = useRouter(); const { replace } = useRouter(); view image here ...