Angular service is able to return an Observable after using the .then method

I am currently facing an issue with retrieving the authentication status in a service method. Everything seems to be working fine except for the return statement. I am struggling with the usage of .then inside .map and I am unable to figure out how to return an Observable.

public getAuthenticationStatus(): Observable<boolean> {
        this._authService.getAuth().map(auth => {
            auth.then(function() {
                return Observable.of(auth.isLoggedIn());
            });
        });
    }
    

I have looked through the documentation and came across a subscribe call. Even after changing it to .map, I still couldn't resolve the issue.

this._authService.getAuth()
        .subscribe(auth => {
    

The error message I keep encountering is

"A function whose declared type is neither 'void' nor 'any' must return a value."

I aim to make this method accessible from any component, similar to the following:

return this._userService.getAuthenticationStatus()
      .map(
        authenticated => {    
          if (authenticated === true) {
            return true;
          } else {
            return false;
          }
        },
        error => console.error('Error fetching user status')
      );
    

Furthermore, I intend to utilize this in an AuthGuard as shown below:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        this._userService.getAuthenticationStatus()
        .subscribe( response => {
            const status = response.isLoggedIn();
            if (status === true) {
               return true;
            } else {
               this.router.navigate(['/login']);
               return false;
            }
        },
        error => {
           console.error('Error fetching user status');
           return false;
        });
      }
    }
    

Answer №1

If you follow these steps, it should do the trick

public confirmUserLoggedIn(): Observable<gapi.auth2.GoogleAuth> {
    return this._gauth.checkAuthentication();
}

When implementing your route guard, make sure to subscribe to the observable and return the result

return this._userService.confirmUserLoggedIn()
  .subscribe( response => {    
      return response.isUserSignedIn.get();
  },
  error => {
     return false
  });

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

Issue with ng-multiselect-dropdown where clearing selected items programmatically does not visually work as expected

Utilizing the ng-multiselect-dropdown, I have encountered an issue where deselecting an option within the object itself clears the selected items visually and in the variable array. However, when programmatically clearing the selectedItems, the variable a ...

What is the method for typing an array of objects retrieved from realmDB?

Issue: Argument type 'Results<Courses[] & Object>' cannot be assigned to the parameter type 'SetStateAction<Courses[]>'. Type 'Results<Courses[] & Object>' lacks properties such as pop, push, reverse, ...

Strategies for Populating Objects in Angular 2

I have a created a complex class hierarchy with multiple classes. I need assistance with populating the "OptionsAutocomplete" object in angular2. Can someone please provide guidance on how to achieve this? interface IOpcionesAutocomplete { opciones ...

Update the child component whenever there are changes in the variables of the parent component in Angular 2

I've implemented a MasterComponent that loads the header, footer, sidebar, and more. The header includes a dropdown with options that are set once the user logs in. I need the header to remain constant even when navigating to different routes, each lo ...

Navigating back to a specific segment of a dataset while using virtual scrolling

Virtual scrolling is a fantastic way to optimize rendering for large data sets. For this particular scenario, I am making use of the Angular Material CDK APIs to implement this feature. However, a specific requirement needs to be addressed - when a user ...

Locate an element within an array of strings to refine the contents of a flatlist

Currently, I have a FlatList that I am attempting to filter using multiple inputs from dropdown selectors. Here is the code snippet for my FlatList component: <FlatList style={styles.list} data={data.filter(filteredUsers)} ...

What is the best way to access and read all @input elements within an Angular component?

Looking to retrieve all properties marked with the @Input() decorator in an Angular component. Attempts using reflect and reflect-metadata have been unsuccessful. Any suggestions on how to achieve this functionality? ...

Steps for associating ngclass with an observant value

Can you bind to an Observable<enum> like this in Angular? <a [ngClass]="{selected: (mapToolBarMode$ | async) === 0 }" /> or <a [ngClass]="{selected: (mapToolBarMode$ | async) === MapMode.Pan }" /> where the observable is named mapTool ...

Creating divs dynamically in a loop and displaying them upon clicking a button in Angular

I am trying to dynamically create divs in a loop and show the selected div when I press a specific button. In theory, this is how I envision it... <div>div1</div><button (click)="showDiv(divID)">showDIV</button> To hide a ...

This code snippet, document.location.search.replace('?redirect=', '').replace('%2F', ''), is failing to execute properly in Firefox

The functionality of document location search replace redirect to another page works in Chrome, however, document.location.search.replace('?redirect=', '').replace('%2F', ''); it does not work in Firefox; instead, ...

Setting a value to a FormBuilder object in Angular 2 with Typescript

During my use of Reactive form Validation (Model driven validation), I encountered an issue with setting the value to the form object on a Dropdown change. Here is my Formgroup: studentModel: StudentModel; AMform: FormGroup; Name = new FormControl("", Va ...

Deploying an Angular 2 application using SystemJS and Gulp can sometimes feel cumbersome due to its

Although I have experience developing with Angular, I recently started working with Angular 2. After completing the quickstarter tutorial, I attempted to deploy the finished application on a server in production mode. My lack of experience with SystemJS a ...

The module '@angular/core/core' does not contain the exported member 'ɵɵFactoryDeclaration'

Hello everyone, We are currently experiencing an issue with our Angular project during the ng build process. An error message is popping up that has us stumped. Despite trying various solutions provided by the GitHub and Stack Overflow communities, we stil ...

The variable is accessed before it is initialized in the context of Next.js and Server Actions

Currently, I am utilizing the new Data Fetching feature in Next JS to retrieve data from an API and store it in a variable named 'contact.' However, I am facing the issue of receiving an error message stating that "variable 'contact' is ...

Getting a variable from outside of the observable in Angular - a step-by-step guide

I have an Observable containing an array that I need to extract so I can combine it with another array. this.builderService.getCommercialData() .subscribe( data=>{ this.commercialDetails = data; this.commercialDetailsArr ...

Having trouble accessing input value when using FormArrayName with FormBuilder?

When attempting to retrieve the value from the input field using formArrayName, I am encountering an issue where it returns null instead. The console shows that I can get the value for client name but not for secrets. What I need is for the returned value ...

How to effectively eliminate the border of a single cell within a Bootstrap Table

Is there a way to remove the border of a single cell in a bootstrap table without affecting the others? I attempted using an id on that specific cell and adding the following CSS code: #borderless-cell { border: 0; } Unfortunately, this solution doesn&ap ...

Angular routes can cause object attributes to become undefined

I am new to Angular and struggling with an issue. Despite reading numerous similar questions and answers related to AJAX, async programming, my problem remains unsolved. When I click on the 'Details' button to view product details, the routing wo ...

Exporting key/value objects with React components as values in Typescript

I have a .tsx file where I need to export an object containing key/value pairs. Each value is going to be a React component used in another file. While I will have multiple key/value pairs, I'm focusing on just one at the moment. object.tsx import { ...

What is the best way to clear a form in a Next.js 13.4 component following a server action?

Currently, I am working on a component using next.js 13.4, typescript, and resend functionality. My code is functioning properly without clearing data from inputs, as it uses the "action" attribute which is commented out. However, I started incorporating ...