Create a new state that contains the user data by calling the getIdTokenResult() function

I am facing difficulty inserting an object and adding it to the state of my application.

My task is to create an object with data fetched from firebase.user and user.getIdTokenResult(true).

For instance:

loggedInUser = {
  uid: user.uid, 
  displayName: user.displayName
  admin: false,
};

const token = await user.getIdTokenResult (true);
loggedInUser.admin = token.claims.admin;

The approach is quite similar to the one above, but I need to accomplish this utilizing only Rxjs operators in order to encapsulate this object within the state of my application.

@Effect

@Effect()
getUser$: Observable<Action> = this.actions$.pipe(
    ofType(auth.AuthActionTypes.GET_USER),
    switchMap(() => this.authService.getUser().pipe(
        map(user => {

            const loggedInUser = {
                uid: user.uid,
                displayName: user.displayName,
                admin: false,
            }

            // **** I need to invoke user.getIdTokenResult() ******
            // and retrieve claims.admin then assign it to loggedInUser object admin.

            // authState = {
            //    uid: user.uid,
            //    displayName: user.displayName,
            //    admin: true, // can be true or false
            // }

            return new auth.Authenticated(loggedInUser);
        }),
        catchError((err => of(new auth.AuthError(err))))
    )

I am still getting accustomed to using reactive programming with Rxjs, hence finding it challenging to merge data from encapsulated Observables.

Answer №1

To preserve the values of the user object within the result of authService.getUser(), consider using .map(). This approach may seem messy, but it gets the job done.

@Effect()
getUser$: Observable<Action> = this.actions$
    .pipe(
        ofType(auth.AuthActionTypes.GET_USER),
        switchMap(() => this.authService.getUser()),
        switchMap(user => user.getIdTokenResult().pipe(map(claims => ({claims, user}))), //map the user to "retain"
            switchMap(({claims, user}) => {
                const userLogged = {
                    uid: user.uid,
                    displayName: user.displayName,
                    admin: claims.admin,
                };
                return new auth.Authenticated(userLogged);
            }),
            catchError(err => of(new auth.AuthError(err)))))

If you need to retain more values, consider exploring Subjects as a cleaner and recommended alternative.

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

Here are the steps to iterate through two arrays and compare them in Angular 2 when the same checkbox is checked

I have two arrays: one containing a list of all office locations, and another with user-selected offices. My goal is to display all the office locations and have the checkboxes checked if they match those in the selected list. Here is how I accomplished th ...

Encountering an error of "Cannot read properties of undefined" while attempting to map GraphQL data in a

I have a dogs component structured like this: const Dogs: React.FC = () => { const { loading, error, data } = useQuery(GET_DOGS); console.log(data) const renderedOption = data ? data.dogs.map(({ dog, index }: { dog:any, index:number }) => ( ...

What are the steps for deploying a TypeScript project based on Koa to AWS Lambda and Azure Cloud Function simultaneously?

I am working on a web application developed using Koa.JS. My goal is to deploy it both on Azure Cloud Function and AWS Lambda so that I can avoid maintenance of server-related tasks and remain flexible with cloud providers. Is there any framework availab ...

Optimizing RxJS Observables for Angular 4

I am facing a challenge with optimizing observables: There are two controls where users can input their username and password. I want to trigger a service method that returns an observable of query results whenever the password field value changes (with a ...

What is the step-by-step guide for implementing an access limiter on an interface

When attempting to modify the access level on an interface in Typescript, I encountered an error stating 'cannot appear in type member.' After removing the access limiter on the interface and implementing it, I tried changing the access limiter o ...

Transform a promise-based function into an observable stream

I'm looking for advice on how to convert a piece of code that uses and returns a promise into an observable. Here is the original code snippet: export const uploadMultipleFilesToAzure = ( uploadData: Omit<UploadMultipleToAzure, 'id'> ...

create an endless loop to animate in angular2

Is there a way to add iterations, or something similar to the ccs3 animation-iteration-count in Angular 2 animations? I've looked but can't find anything related. How can we apply an infinite play to the animation? Where should we include that o ...

Generating a dynamic SQL Update statement using an array of objects

I am currently working with an array of objects in order to create an Update SQL statement. Here is the array I am using: let dataUpdate = [ { "field1":123, "field2":"BMW", "field3":"blue" ...

Components in Angular do not refresh after using router.navigate

I currently have two main components in my Angular project: users.components.ts and register.components.ts. The users.components.ts displays a table of users, while the register.components.ts is where users can be added or edited. After making changes to ...

Converting a string into a TypeScript class identifier

Currently, I am dynamically generating typescript code and facing an issue with quotes in my output: let data = { path: 'home', component: '${homeComponentName}', children:[] }; let homeComponentName = 'HomeComponent' ...

A guide on integrating a service into another service and utilizing it in exported constants or interfaces within Angular

My goal is to utilize a service within another service in order to translate strings found within exported constants. This is how my code currently appears in a simplified form: // Imports.. @Injectable( { providedIn: 'root' } ) export class ...

Steps to resolve: The term is not callable. The type '{}' does not have any call signatures.ts(2349)

Hello everyone, I am currently encountering a type error in my login file due to my limited familiarity with typescript. The issue arises when attempting to assign the response from the API to the user variable within my handleLogin function, where user re ...

Deactivate the react/jsx-no-bind warning about not using arrow functions in JSX props

When working with TypeScript in *.tsx files, I keep encountering the following error message: warning JSX props should not use arrow functions react/jsx-no-bind What can I do to resolve this issue? I attempted to add configurations in tslint.json js ...

Enhance your Typescript code with a type guard that supports optional wrapped types

I haven't come across a question similar to this one before. My goal is to develop a type guard that can accurately determine the type of a specific variable. It's quite simple with a single type. type A = { id: number, title: string, type: stri ...

Error: Reference to an undeclared variable cannot be accessed. TypeScript, Cordova, iOS platforms

Can anyone offer some advice on what might be the issue? I'm encountering an error while building my Ionic app on the IOS platform, but everything is running smoothly on Android. ReferenceError: Cannot access uninitialized variable. service.ts:31 O ...

Using an array of functions in Typescript: A simple guide

The code below shows that onResizeWindowHandles is currently of type any, but it should be an array of functions: export default class PageLayoutManager { private $Window: JQuery<Window>; private onResizeWindowHandlers: any; constructor () { ...

Detecting if a string is in sentence or title case with a typeguard

When setting the sameSite property of a cookie, it must be either Strict, Lax, or None. However, the package I'm using uses lowercase values for this attribute. Therefore, I need to adjust the first letter of the string: let sentenceCaseSameSite: &quo ...

Changing the value of an element in an array using typescript within an Angular context

I am currently working with Angular 5 and I have a task to update the array values based on the selectedMobile array. Below is my code snippet: const mobilelist = [ { 'key': 'apple', 'name': 'Apple', 'check ...

Issue with Dates in Typescript array elements

When attempting to compare different Date elements in my code, I encountered an issue. I have two date elements representing date formats but am unable to compare them because I keep receiving the error message "core.js:6237 ERROR TypeError: newticketList. ...

Developing an angular 6 web client for GRPC

Having experience with grpc using a .net client and a Java grpc server, how can I integrate a grpc web client on Angular 6 using TypeScript? Additionally, what is the process for creating proto files and their typings for TypeScript? I have been referenci ...