Service function in Angular 2 is returning an undefined value

There are two services in my project, namely AuthService and AuthRedirectService.

The AuthService utilizes the Http service to fetch simple data {"status": 4} from the server and then returns the status number by calling response.json().status.

On the other hand, AuthRediredService implements the OnActivate interface and relies on the AuthService. While there is only one method within AuthService called GetStatus(): number, it unfortunately returns undefined.

AuthService

GetStatus(): number {
    let status: number;
    this.http.get(this.host + "/api/auth/")
    .subscribe((value: Response) => {
      status = value.json().status;
      console.log(value.json().status); // showing the actual number 4
    });
    return status; // 4
  }

AuthRedirectService

canActivate() : boolean
{
    console.log(this.auth.GetStatus()); // shows undefined !!!!!!!!
    if(this.auth.GetStatus() == StatusCode.Logined)
    {
        // redirect logic here
        return false;
    }
    return true;
}

Answer №1

This particular issue involves a straightforward Javascript asynchronous problem and is unrelated to Angular2.

When working with javascript, executing an async method, such as making an http call that may take 10 minutes to resolve, means you cannot expect to receive the result immediately:

Consider this scenario:

   myAsyncFunction(){
       let theResult;  // First: this line executed
       callAHttpServiceThatTakes1Minute() // Second: we invoke the function that will return the result in 1 minute
       .then((res)=>{
          theResult = res; // Fourth :  will be available after 1 minute 
       });

       console.log(theResult); // Third : This returns undefined because step Four has not completed yet.
   }

To resolve this issue, adjust your routing configuration like so:

 { path : 'home' , component : HomePageComponent , resolve : { user : GetStatusResolver } } ,

Then create the following resolver:

@Injectable()
export class GetStatusResolver implements Resolve {
    constructor ( private auth : AuthService ) {
    }

    resolve ( route : ActivatedRouteSnapshot , state : RouterStateSnapshot ) : Observable<User> {
        return  this.auth.GetStatus() ;
    }
}

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

Unable to remove loading.tsx file

Currently tackling a project using Next.js, I decided to include loading.tsx within the app directory. However, upon attempting to delete it, an error crops up: Caused by: The system cannot find the file specified. (os error 2) The import trace for the r ...

Navigating with the Angular router to a child route is causing a redirection to the 404

I'm facing a challenge with navigating to a child component from the parent view. This is how my app-routing configuration looks: const routes: Routes = [ { path: '', redirectTo: 'home', pathMatch: 'fu ...

Perform a delayed evaluation of the length of the @Input() array

In my Component, I am utilizing an @Input() ids: string[] = []; variable to check if the length equals 1 in the DOM. <mat-expansion-panel *ngFor="let id of ids" [expanded]="ids.length === 1"> ... </mat-expansion-panel> However, when I append ...

The functionality is verified in Postman, however, it is not functioning properly when accessed from my client's end

I am working on a project where I have a button in my client's application that is supposed to delete a document from a MongoDB collection based on its ID. Here is the backend code for this functionality: index.js: router.post('/deletetask' ...

OpenID Connect does not provide confirmation when handling user logouts

We have integrated the angular-oauth2-oidc plugin into our system. Specifically, we are using: angular 13 angular-oauth2-oidc 13.0.1 Our OAuth IDP is WSO2 Identity Server, and here is a sample of the discovery service implemented by WSO2 IS: { // ...

The absence of @angular/compiler in the bundle file is causing an issue with Angular es

I've developed a shell application that operates using and https://github.com/systemjs/systemjs to manage its various micro-frontends. Recently, I created a new Angular application and aimed to integrate it with the esBuild builder tool. Upon runni ...

Ways to Execute the Constructor or ngOnInit Multiple Times

Here's the scenario I'm facing: I have developed an app with multiple screens. One of these screens displays a list of articles. When a user clicks on an article, they are directed to another screen that shows the details of that specific item. ...

Setting up the environment variable for ApolloClient to be utilized in server-side rendering for continuous integration/continuous deployment involves following a specific

My apolloClient is configured as follows: /** * Initializes an ApolloClient instance. For configuration values refer to the following page * https://www.apollographql.com/docs/react/api/core/ApolloClient/#the-apolloclient-constructor * * @returns Apoll ...

Utilizing Typescript template strings for data inference

In coding practice, a specific convention involves denoting the child of an entity (meaning an association with another entity) with a '$' symbol. class Pet { owner$: any; } When making a reference to an entity child, users should have the opt ...

The test failed to execute due to disconnection (0 occurrences) as no message was received within the 30000 ms timeframe

Currently, I am facing an issue with my Angular application. When I execute the "ng test" command, it displays an error message stating 'Disconnected (0 times), because no message in 30000 ms.' I have tried updating both karma and jasmine package ...

Angular 9 introduces a new feature where canActivate now supports Observable<boolean> which provides a more robust error handling mechanism for failed

Currently, I am working with angular9 and rxjs6 while implementing canActivate: Observable feature. However, I encountered an error when attempting to use catchError, as shown in the image below: Is there a solution to fix this issue? I have already tried ...

Sorting and categorizing RxJS Observables

Learning about reactive programming is a new and sometimes challenging experience for me. If we have a list of events from a service called event[] The structure of an event is as follows: Event: { beginDate: Date, name: string, type: State } State: ...

When utilizing Monggose, Angular, and Node, a route containing the deleteOne method repeatedly reports that the object has been successfully deleted, despite the delete count remaining

I've encountered a similar issue to others, but their solutions didn't work for me. I'm working on a small MEAN app with mongoose and facing a problem when trying to delete a user or any other object stored in the collection. The route seems ...

IntelliJ is indicating a typescript error related to react-bootstrap-table-next

Working with react-bootstrap-table-next (also known as react-bootstrap-table2) has been causing a Typescript error in my IntelliJ environment, specifically on the validator field within my column definition. Despite trying various solutions, such as adding ...

Creating a specialized TypeScript interface by extending a generic one

Create a customized interface using TypeScript that inherits from a generic interface by excluding the first parameter from all functions. Starting with the following generic interface: interface GenericRepository { insertOne<E>(entity: Type<E& ...

Playing around with TypeScript + lambda expressions + lambda tiers (AWS)

Having trouble importing modules for jest tests in a setup involving lambdas, lambda layers, and tests. Here is the file structure: backend/ ├─ jest.config.js ├─ package.json ├─ babel.config.js ├─ layers/ │ ├─ tsconfig.json │ ├ ...

Maximizing Azure Web App capabilities to host multiple applications

I have developed an app using ASP .NET Core MVC + Angular and now I need to deploy it for three separate customers. Each customer currently has their own database. Is it feasible to create multiple sites within a single Azure web app (such as mysite.com/ ...

MaterialUI Divider is designed to dynamically adjust based on the screen size. It appears horizontally on small screens and vertically on

I am currently using a MaterialUI divider that is set to be vertical on md and large screens. However, I want it to switch to being horizontal on xs and sm screens: <Divider orientation="vertical" variant="middle" flexItem /> I h ...

Undefined error when refreshing Angular page

One particular page on my forum-like website is causing issues with refreshing. In my project, users can log in, view their profiles as well as others'. However, when I refresh a profile page, no data loads from the server and an error appears in the ...

Prevent HTTP using AsyncValidator when the value is empty

I have developed a custom AsyncValidator to verify the uniqueness of a userName. Inspired by this tutorial, I have implemented a delay of 500ms. However, I am facing a challenge in preventing the HTTP service call if the input value does not meet a speci ...