How can I ensure that a user variable stored in an Angular6 service remains defined and accessible from other components?

Currently, I am working on an Angular app and facing a challenge. After receiving a user variable from an asynchronous call to Firestore Cloud, I noticed that the variable is successfully set (verified using console.log()). However, when I navigate between pages and attempt to load the recipes associated with that user on Firestore, it indicates that the user variable is undefined.

Is there a more effective approach to handle this situation?

Thank you

EDIT: Code

tryConnect(email: string, password: string) {
// u = array of users
this.usersWithId.subscribe(u => {
  for (const a of u) {
    console.log(a);
    if (a.email === email && a.password === password) {
      this.connectedUser = a;
      console.log(this.connectedUser);
      break;
    }
  }
});

}

addRecipe(recipe: Recipe) {
console.log(this.connectedUser);
this.db.collection('/recipes').add({
  name: recipe.name,
  description: recipe.description,
  meal: recipe.meal,
  steps: recipe.steps,
  servings: recipe.servings,
  cuisine: recipe.cuisine,
  userID: this.connectedUser.userID,
  ingredients: recipe.ingredients
});

Answer №1

If you're looking to accomplish a task, consider utilizing a state management system like rxjs/store. This allows you to store data throughout your application and have it synchronized wherever it's accessed.

Another alternative is using sessionStorage or localStorage for saving data across different sessions.

Answer №2

If you're not already utilizing it, my recommendation would be to incorporate @angular/fire.

Here's a method to make use of @angular/fire for your intended purpose.

Once injected as a dependency, AngularFireAuth provides an authState property that holds an Observable<firebase.User>. This represents the current login status of the user.

In your service, you can establish a private

BehaviorSubject<Observable<firebase.User>>
, where the next function will trigger upon any change in authState.

You can then expose this

BehaviourSubject<firebase.User>
using asObservable. By doing so, any component that utilizes your service as a dependency will have access to the user$ Observable to subscribe and obtain the current user's status.

Below is how you can implement this functionality in code:

import { AngularFireAuth } from '@angular/fire/auth';
import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject } from 'rxjs';
import { switchMap } from 'rxjs/operators;

import { User } from '@app/shared/models/user.model';

@Injectable()
export class AuthService {

  private user: BehaviorSubject<Observable<firebase.User>> = new BehaviorSubject<Observable<firebase.User>>(null);
  user$ = this.user.asObservable().pipe(switchMap(user => user));

  constructor(
    private afAuth: AngularFireAuth
  ) {
    this.user.next(this.afAuth.authState);
  }

  loginViaCredentails(user: User) {
    return this.afAuth.auth.signInWithEmailAndPassword(user.email, user.password);
  }

  ...

}

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

After the transition from Angular 8 to Angular 9, an issue arose with the node_modules/@zerohouse/router-tab/zerohouse-router-tab.d.ts file, as it was not declared

Error Image package.json { "name": "client", "version": "0.0.0", "license": "MIT", "scripts": { "ng": "ng", "serveapp": "ng serve ...

Struggling to configure a firebase adapter with nextauth on the application router. Despite attempting to sign up, it fails to generate a session or store the user information

When attempting to create a user in the Firestore database using NextAuth adapter for Firebase, I am consistently unauthorized when utilizing the adapter. The user is not successfully created in the database; however, it does work when the adapter is remov ...

Utilizing group by date feature in Angular ag-Grid

I'm working on setting up an ag-grid with columns for date, time, and location. Below is the code snippet: list.component.ts columnDefs: any = [{ headerName: 'Date', field: 'date', valueFormatter: (data: any) => { ...

The pre-line white-space property is not functioning as anticipated in my CSS code

content: string; this.content = "There was an issue processing your request. Please try using the browser back button."; .content{ white-space: pre-line; } <div class="card-body text-center"> <span class="content"> {{ content }} </span& ...

Angular - next steps following a service request

In my current Angular 14 project, I am developing a page that loads content. Some of this content is obtained from an external service call, and while waiting for the data to load, I have implemented a loading screen. On the loading spinner, I have includ ...

"Connection refused on local server when trying to connect Node.js with Angular

My Mean app is deployed on bitnami. When attempting to make a post from angular to my express server, I use the URL http://localhost:3000/mypostaccess. Every time I try this, my browser shows net::ERR_CONNECTION_REFUSED. Strangely, when I replace "localho ...

Is it possible to utilize an array of numbers as a data source in ng2-smart table?

Hey there, I'm currently facing an issue with populating ng2-smart-table with an array of numbers. When I try to display the table, all I see is 6 empty rows like this: https://i.stack.imgur.com/DZJjq.png Here's the code for the table: <ng2- ...

Issue with ReactJS Typescript: Cannot assign type 'number' to type '0, 8, 16, 24, 32, 40, or undefined'

I am looking to implement a grid from material-ui in react using typescript. You can view the live demo here. I have made adjustments to the example to make it work with typescript. Here is how my demo.jsx file looks like: import { withStyles } from &apo ...

Combining angular's CLI project with a groovy Gradle application

I'm in the process of merging the seed project from angular-cli with my Gradle-packaged Java application, deployed on a Tomcat server. How can I successfully combine the Angular build with the Gradle build? Additionally, where is the ideal location t ...

During the process of adding a new template to my Angular project, I came across an issue within the core.min.js and script.js files

index.html <html class="wide wow-animation" lang="en"> <body> <app-root></app-root> <!-- Javascript--> <script src="assets/js/core.min.js"></script> <script src="assets/js/script.js"></script& ...

How to dynamically assign tab indices in Angular's mat-tab-group using ngFor

In my angular web application, I have a tab group that requires a mandatory tab (for posting a new object) and dynamic tabs (for editing existing objects). I am looking to set specific tabindex values for the dynamic tabs in order to have one of them disp ...

Leveraging the power of TypeScript and Firebase with async/await for executing multiple

Currently, I am reading through user records in a file line by line. Each line represents a user record that I create if it doesn't already exist. It's possible for the same user record to be spread across multiple lines, so when I detect that it ...

Dealing with NPM problems during Angular 9.0.7 setup issues

I encountered a problem after a recent Windows update that corrupted my system. I had to reinstall Windows, and now I am unable to run my Angular project, which was originally in version 9.0.7 with a package.json file. I tried installing Angular 9.0.7 glob ...

Utilize the power of generics with Angular's service providers

Is it possible to make the membervar of class Parent generic instead of type any, while still retaining the ability to switch provider classes without having to update all components that rely on class Parent? For example, if class ChildB implements a diff ...

Using Typescript to define unions with multiple callback types

While in the process of converting my code to TypeScript, I encountered a dilemma. I created a generic foreach function that can handle arrays and objects, with different types of callbacks for iteration. However, I'm unsure how to specify the type wh ...

Error message in Angular 2: Unable to locate node module for import

Recently, I encountered an issue while attempting to utilize a specific node module called aws-api-gateway-client Although the installation was successful, I am facing difficulties with importing this module due to an error. Oddly enough, it works seamle ...

Error: An unexpected token < was caught in the TypeScript Express code

Using TypeScript to compile and run an Express server that simply serves an HTML file. However, encountering an error in the response under the network tab in Chrome for app.js: Uncaught SyntaxError: Unexpected token '<' Below is the server c ...

Issue with accessing custom read/write location during runtime in ngx-translate HTTP loader

After logging in, I need to load JSON files and then download a file at a specific location using a custom HTTP loader (TranslateHttpLoader). The assets/i18n/ folder is not writable with fileSystemModule.knownFolders.currentApp(), so I tried using fileSyst ...

Using TypeScript with Angular-UI Modals

Currently, my goal is to create a modal using angular-ui-bootstrap combined with typescript. To begin, I referenced an example from this link (which originally utilizes jQuery) and proceeded to convert the jQuery code into typescript classes. After succes ...

Personalize the Ag-Grid Status Bar to your liking

Currently utilizing Ag-Grid Enterprise, Version 19 ("ag-grid-angular": "19.0.0", "ag-grid-community": "19.0.0", "ag-grid-enterprise": "19.0.0") in conjunction with Angular 4. There is a specific need to customize the status bar of the grid and add an add ...