What is the best way to store a global visible user in an Angular 2 application?

Upon logging in, I am able to retrieve the user.

  private login() {
    let data = { "UserName": "admin" , "Password": "+" };

    this.apiService.doLogin(data).subscribe(
      (res) => this.userService.set('user', res),
      (err) => console.log(err)
    )
  }

How can I effectively implement this userService? * Is there a way to fetch user data without making a new call to the back end? ** I am aware of https://github.com/ngrx/store, but perhaps there is a better solution out there?

Answer №1

If you're looking to store the details of your logged-in user, there are a few options available to you.

Using Redux Store (ngrx):

You can utilize the ngrx store concept by visiting https://github.com/ngrx/store. Simply retrieve your user model from the backend and dispatch an action to load the data.

Advantages:

  • You can subscribe to your user store in various parts of the application, enabling you to react effectively to any changes,
  • The user model in the store remains immutable - any modifications require triggering an action that triggers a pure reducer function, preventing accidental alterations to user data.

Using a Service:

An alternative approach is to store your user model object as a private variable within a service.

Disadvantages:

  • In Angular 2, services can be either global or module-scoped. This means that if you mistakenly include your user service in both the global module providers array and as a feature module provider, Angular 2 will create two instances of your service, potentially leading to issues such as having one instance with empty user data. A similar problem is discussed here: https://angular.io/docs/ts/latest/guide/ngmodule.html#!#q-why-it-is-bad

Answer №2

Utilizing HTML5's local storage capabilities is a possibility, however when working with Angular2, ngrx/store presents a more robust solution. It includes advanced state management features making it the preferred choice for handling data within an Angular application.

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

Checking the types of arrays does not function properly within nested objects

let example: number[] = [1, 2, 3, 'a'] // this code block correctly fails due to an incorrect value type let example2 = { demo: 1, items: <number[]> ['a', 'b'], // this code block also correctly fails because of ...

Iterating over elements with a custom width using ngFor in Bootstrap

I'm currently using *ngFor to cycle through multiple images as the background of each column in a row using Bootstrap. One thing I'm wondering is how to control the width of each column. For example, if I have 10 images, how can I adjust the widt ...

"Enhance your Angular configuration with the powerful ngBootbox plugin

Is there a way to permanently change the locale of ngBootbox? I tried adding an extra angular configuration: var app = angular.module('some_module', ['highcharts-ng', 'ui.router', 'oc.lazyLoad', 'ui.selec ...

Validation of decimal numbers in JavaScript without the presence of any other characters

Looking to create a JavaScript regex to validate an 8-digit number that may include decimals. The current regex /^\d+$/ allows for any other characters such as ( , * $ etc. How can I modify this to only accept numbers and periods? For example, the nu ...

NextJS and Context API throwing a Typescript error

I've been working on my _app.tsx file and here's the code snippet I have: import React from 'react' import type { AppProps } from 'next/app' /* Import Styles */ import '@themes/index.scss' /* Import Template */ imp ...

Transmit data using $http post request in Angular to assign values to a key in a PHP array

Need help with sending an Object to PHP using POST and converting it into an associative array sendData: function(myWord, myDescription, myTranslation) { var formData = { w: myWord, d: myDescription, t: my ...

Fetching data from a URL using AngularJS while the view is being loaded

Struggling to perform an API call when loading a specific view. controllers.controller("detailsCtrl", ["$scope", "$routeParams", "$filter", "$http", function($scope, $routeParams, $filter, $http) { $scope.getCurrent = function(url, id, callBack, apiCal ...

Combining Typescript interfaces to enhance the specificity of a property within an external library's interface

I have encountered a scenario where I am utilizing a function from an external library. This function returns an object with a property typed as number. However, based on my data analysis, I know that this property actually represents an union of 1 | 2. Ho ...

The existing object contains a value, however, attempting to access its property results in an undefined value being

I have discovered some unusual occurrences in my coding. Specifically, I have an AuthService that handles authentication requirements for my applications, including the authentication token. @IonicPage() @Component({ selector: 'page-login', ...

Check the present value of Subject.asObservable() within an Angular service

I am working on developing a basic toggle feature within an Angular2 service. To accomplish this, I require the current value of a Subject that I am observing (shown below). import {Injectable} from 'angular2/core'; import {Subject} from ' ...

Question from a student: What is the best way to transfer information between different classes?

Currently, I am delving into SPFX development. My focus is on constructing a form that incorporates multiple classes in order to gain insight on how they can interact and share data among one another. In this scenario, I have established two distinct clas ...

What could be the reason for the click event returning undefined?

I can't seem to pass a date from a mat-option choice as it returns undefined when I try to log the event in the click method. How can I solve this issue? HTML <mat-drawer-content class="Font"> <mat-form-field appearance=& ...

Issue with vue-class-component: encountering TS2339 error when trying to call a method within

My vuejs application is being built using vue-cli-service. After a successful build, I encountered TS2339 errors in my webstorm IDE: Test.vue: <template> <div>{{method()}}</div> </template> <script lang="ts"> impor ...

Combining input with a space character

I came across this code in an AngularJS filter. Can someone explain its purpose? input = input || ' '; https://docs.angularjs.org/guide/filter ...

Verifying the existence of an optional property on my component using Jest

One of the props in my component is called jsonpayload, and it is optional. Here's how it looks in the interface: export interface props { jsonpayload?: payload[] onclick: () => void; } My Jest file: const test_prop: dummy_props ...

Customizing the login page of Thinktecture Identity Server v3 to include a loader feature

I have customized the default login view by incorporating my own file here: https://i.sstatic.net/pD2Ti.png My approach involves extracting the base file from the repository assets and making some adjustments to align it better with the requirements of m ...

Failure to trigger VS code extension functionality

After much thought, I've decided to embark on creating my own VS Code extension specifically for TypeScript/Angular code snippets. The first snippet I've developed is called Forloop.snippet: const ForLoopSnippet = 'for (let {{iterator}} = { ...

Using a number input with step increments of 0.01 in AngularJS can result in undefined values for specific inputs

An issue arises when using a specific type of input in angularjs (1.6.1) where the values between 9.03 to 9.05 inclusively return undefined. This problem also occurs with other values like 9.62, 9.63, and 17.31. <input type="number" step="0.01" data-ng ...

Command to exclude the processing of an element during compilation

I'm working on creating a custom directive named ng-ignore that will block the HTML compiler from processing an element and its children. While I've been honing my skills in directive writing, this particular one has me a bit puzzled. My object ...

Issues with Meteor-Angular 1.5 service functionality

I've been struggling to develop a code-sharing service between two different components in Meteor 1.3, but so far I haven't had much success. Trying to create and inject Angular 1 services just doesn't seem to be working. This is what my An ...