Is it feasible to assign a value to a variable in Angular based on the data returned from a subscription?

somefunction(){
    isUserLoggedin(): boolean {
        this.isUserInDB().subscribe((result: any) => {
          if (result.code === 200) {
            return true;
          }
        });
      return false;
  }

isUserInDB(): this API takes a token from localstorage and returns 200 if the user exists in DB or returns 404 if the user does not exist in DB (someone is trying to try his/her own token.)

In this scenario, I always end up receiving false because the first return statement gets executed before the subscribe method. Is there a different approach I should consider, or am I just overcomplicating things?

Answer №1

Set a class property to false initially:

isUserInDatabase = false

Upon component creation, update the property to true if the response is successful:

ngOnInit() {
    this.checkUserInDatabase().subscribe((response: any) => {
        if (response.statusCode === 200) {
            this.isUserInDatabase = true;
        }
    });
}

Answer №2

Due to the asynchronous nature of this.isUserInDB(), the function isUserLoggedin will always return false. One way to handle this is by returning the observable instead of a boolean, and managing it where the function is called:

isUserLoggedin(): Observable<any> { // replace any with your type
    return this.isUserInDB();
}

Whenever you need to execute tasks based on user login status, you can subscribe to this function and carry out your operations:

isUserLoggedIn.subscribe((result: any) => {
          if (result.code === 200) {
             // Your code
          }

It is recommended that in your login process, you store the user's login status in a service and return it accordingly.

Answer №3

My approach would be to synchronize it using async/await functionality.

async checkIfUserLoggedIn(): Promise<boolean> {
   const result = await this.verifyUserInDatabase().pipe(first()).toPromise();

   if (result.code === 200) {
      return true;
   } else {
      return false;
   }
}

Example of how to use it:

async someFunction(): Promise<void> {
    const isLoggedIn = await this.checkIfUserLoggedIn();
}

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

Implementing context menus on the Material-UI DataGrid is a straightforward process that can enhance the user experience

I am looking to enhance my context menus to be more like what is demonstrated here: Currently, I have only been able to achieve something similar to this example: https://codesandbox.io/s/xenodochial-snow-pz1fr?file=/src/DataGridTest.tsx The contextmenu ...

Utilize ngModel to access input files in the array

Within my form, there is a file upload input: <input type="file" [(ngModel)]="item.image" name="image" #image> Can I retrieve #image.files[0] using the ngModel item.image directly (without creating a reference)? If not, what exactly does ngModel s ...

Exploring the functionalities of Angular components

I have encountered an issue while testing my class that relies on a single dependency, which is a service. Despite trying various methods such as using stubs, I am still facing the problem of an undefined method. https://i.stack.imgur.com/A3by2.png Testin ...

The 'SVGResize' or 'onresize' property is not available on the 'SVGProps<SVGSVGElement>' type

Using React with SVG I'm facing an issue with handling the resizing event of an svg element. I have looked into using the SVGResize and onresize events, but encountered compilation errors when trying to implement them: const msg1 = (e: any) => co ...

Issue with TypeScript: Error appears when importing express after running "npm i @types/express -D"

Struggling with adding the following line of code in an index.ts file: import express, { Application } from 'express'; Initially encountered an error with "from 'express'", so I ran npm i @types/express -D which fixed that is ...

When Ionic Angular app's IonContent scroll element returns an incorrect scrollTop value after navigation completes, what might be the reason behind this unexpected behavior?

In my quest to scroll the ion-content component to the top upon navigating to the page from certain selected pages, I have implemented a solution using the router's NavigationEnd events. However, I have encountered an issue where the IonContent's ...

Improving Performance with Reusing Selectors in Ngxs

Working with Angular using the container/presentation pattern and Ngxs presents a challenge for me. The issue I am facing is that I have one container component nested within another container component, both calling the same @Select: @Select(State.example ...

How can Firebase and Ionic be used to customize the password reset template for sending verification emails and more?

I'm facing an issue with firebase's auth templates not supporting my native language. Is there a way to customize the password reset template to also handle verification and email address change emails? ...

ESLint not functioning properly on TypeScript (.ts and .tsx) files within Visual Studio Code

After installing the ESLint extension in VSC, I encountered an issue where it was no longer working on the fly for my React project when I introduced Typescript. In the root of my project, I have a .eslintrc file with the following configuration: { "pa ...

Using Typescript to set the image source from a pipe

I've been working on creating a custom pipe similar to the code below: @Pipe({ name: 'imagePipe' }) @Injectable() export class ImagePipe { constructor(public someService: SomeService, public storage: Storage) { } transform(value: ...

HTML template failing to retrieve data from Angular dataSource

My goal is to import data from an Excel file into my angular application. I have successfully retrieved the data from the Excel file, parsed it to extract the necessary columns, and stored it in an array within my service.ts file. I call the service from ...

Angular: Merge two Observables to create a single list and fetch the combined data

I am currently working on creating a function that returns an observable with a list, compiled from several observables. I feel like I am very close to finding the solution because the debugger stops right before displaying the list. Here is my code: ts t ...

Instantiate a fresh object with its own set of functions

I've been struggling with implementing the OnPush change detection strategy. Here is an example of a class I have: class Item { private name; private _valid; public set valid(valid) { this._valid = valid; } constructor(name) { th ...

TS2531: Nullability detected in object when using .match() method

I'm encountering a linting error on fileNameMatches[0] in the following code snippet. Strangely, the error doesn't appear on the Boolean() check. Even if I remove that check, the issue remains unresolved. Can anyone suggest a solution? protected ...

Collapsible list in Angular2 sidenav: ensuring only one sublist remains open

Presenting a functional sidenav demo with Angular 2, TypeScript, and Material Design components. The sidenav features a UL, with the Sites and Users anchors expanding to display their own sub-list. Check out the Plunker here Here is the HTML code for the ...

Leveraging the `--max-http-header-size` flag with ts-node

Encountered an issue when trying to use ts-node with the --max-http-header-size 15000 flag. It works fine with regular node, but unfortunately, ts-node does not support that option ...

What is the best way to obtain a comprehensive list of nested routes specified in the router configuration?

In my Angular 2 App, I have a dashboard route that contains several child routes. { path: 'app/:property', component: DashboardComponent, canActivate: [AuthGuardService], children: [ { path: 'home', component: HomeComponent } ...

Generate an auto-focus Power BI report seamlessly and effortlessly

I'm working on a straightforward Microsoft Power BI example that showcases a list of employees grouped by gender. <iframe width="300" height="200" src="https://app.powerbi.com/view?r=******" ></iframe> The issue I am facing is that the ...

WebStorm disregards tsconfig compiler directives when working with Angular applications

My project structure was created using angular-cli, which includes a root tsconfig.json, src/tsconfig.app.json, and src/tsconfig.spec.json. Despite having the noImplicitAny and strict options enabled in the root configuration, I do not receive error notifi ...

typescript class that utilizes a function with multiple shapes (overloading) and generics

TYPESCRIPT playground Is there a concept similar to Overloads for classes? I encountered an issue with the creation of createRequest.ts and the function should be error-free. I am looking to apply the same generics used in the createRequest function to th ...