Sharing an Angular 2 class instance across components

As a beginner with Angular 2, I'm adapting well so far. However, I've encountered a problem (possibly due to my familiarity with Angular 1) - I need the class "User" to be global and accessible across different components.

Currently, I have a User class and I'm logging in the user in one component.

@Component({
  selector: 'login',
  templateUrl: 'app/login/login.html',
  providers: [User]
})
export class loginComponent {
  submitted = false;
  username  : string;
  password  : string;
  constructor(public user : User){}
  onSubmit(event) { //form event
    event.preventDefault();
    this.user.login(this.username,this.password, () =>{this.router.navigateByUrl('dashboard')}

The login method in the user class is updating the internal variables of the user, such as name and last name. I have a different component assigned to the dashboard route in the router. However, when I import User, a new instance of the class is created. How can I maintain the data in the class?

Answer №1

To start off, my recommendation is to utilize the 'UserService' instead of just 'User'.

If you are seeking Application-wide dependencies, it's essential to provide them at a higher level, ideally within your AppComponent or AppModule.

In essence, whenever you include a service in the providers array in your application, a new instance will be utilized in that component and any child components.

Therefore, by defining the provider in the AppComponent rather than in the loginComponent, you will have the same instance accessible for injection.

I hope this explanation clarifies things for you!

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

An issue has occurred while attempting to differentiate '[object Object]'. Please note that only arrays and iterable objects are permitted

myComponent.component.ts ngOnInit() { this.getData.getAllData().subscribe( response => { console.log(response); this.dataArray = response; }, () => console.log('there was an error') ); } myservi ...

Include a fresh attribute in the Interface

How can I include a boolean property isPhotoSelected: boolean = false; in an API interface that I cannot modify? The current interface looks like this: export interface LibraryItem { id: string; photoURL: string; thumbnailURL: string; fi ...

utilizing Typescript object within an array of objects

How can I optimize typing this nested array of objects? const myItem: Items[] = [{ id: 1, text: 'hello', items: [{ id: 1, text: 'world' }] }] One way to approach this is by using interfaces: interface It ...

A guide on efficiently utilizing combineLatest and mergeMap for handling multiple subscriptions

As I continue to delve into the world of rxjs, I've encountered an issue with managing multiple subscriptions. Specifically, I'm struggling to extract an ID from a response in order to correctly associate photos with products. create(product) { ...

What is the best way to determine the amount of distinct elements in an array of objects based on a specific object property?

I am working with an array called orders. orders = [ {table_id: 3, food_id: 5}, {table_id: 4, food_id: 2}, {table_id: 1, food_id: 6}, {table_id: 3, food_id: 4}, {table_id: 4, food_id: 6}, ]; I am looking to create a function that can calculate ...

What are the steps to resolve routing issues within an Angular component integrated into an ASP.NET Core web application?

When it comes to routing in Angular, I have been following the Angular tutorial from documentation. My example application integrates Angular components with an ASP.NET Core 2.2 web app, and these components are displayed within .cshtml views. I use Angul ...

What methods can be used to block direct attribute updates in a JS/TS class?

class Creature { secretProperty modifySecretProperty(value) { this.secretProperty = value } } new Creature().modifySecretProperty('hidden way') //success new Creature().secretProperty = 'not permitted' // failure To r ...

Execute TypeScript on the Angular project's specified version

Is there a way to efficiently manage multiple projects on the same computer that require different versions of Angular? Can I specify the version of Angular within the package.json file to avoid conflicts? ...

Attempting to add a new property to every object in an array using TypeScript

In my Angular project, I have a specific code block that retrieves an array of objects containing contact records. Within a 'forEach' loop, I am generating a new field for each contact record to store the user's initials. The goal is to ad ...

The application of *ngComponentOutlet ngModuleFactory is unreliable when deployed in a production environment

While working on Angular 4, I utilized ngComponentOutlet to create dynamic components. In the development environment, my code functions properly but encounters issues in production. @Component({ selector: 'dynamic-detail', template: `<ng ...

What is the Ideal Location for Storing the JSON file within an Angular Project?

I am trying to access the JSON file I have created, but encountering an issue with the source code that is reading the JSON file located in the node_modules directory. Despite placing the JSON file in a shared directory (at the same level as src), I keep r ...

What is the best way to configure Apache to act as a reverse proxy for an ASP.NET Core API and an Angular

My aspnet core api is running on localhost:8080 (kestrel) and functions perfectly on localhost:80 (apache reverse proxy), making it accessible from the internet via www.example.com. I am looking to deploy my angular client on the same port locahost:80(www ...

Select a random index and modify it until all unique options have been exhausted, then restart the process

My image gallery has 6 slots for images, and I have an array with a certain number of image objects: "src" : { "1x" : "/clients/Logo-1.png", "2x" : "/clients/<a href="/cdn-cg ...

The Formly form is experiencing a glitch where it does not reflect the updated default value of

My goal is to dynamically update the Formly form rendering based on changes made in the form scheme (which consists of an array of FormlyFormConfig objects). I have noticed that the updating works when adding a new object or modifying a field label, but it ...

What are the benefits of pairing Observables with async/await for asynchronous operations?

Utilizing Angular 2 common HTTP that returns an Observable presents a challenge with nested Observable calls causing code complexity: this.serviceA.get().subscribe((res1: any) => { this.serviceB.get(res1).subscribe((res2: any) => { this.se ...

Managing Angular Universal in a production environment can be a challenging task

I am currently working on a project that utilizes the MEAN stack. Front-end: Angular 6.*. Backend: ExpressJs and Mongodb. During development, Angular runs on port 4200, while ExpressJs runs on port 3000. For production, I build Angular and serve it as ...

transmit data from Node.js Express to Angular application

I am making a request to an OTP API from my Node.js application. The goal is to pass the response from the OTP API to my Angular app. Here is how the API service looks on Angular: sendOtp(params): Observable<any> { return this.apiService.post(&q ...

During rendering, the instance attempts to reference the "handleSelect" property or method which is not defined

I've incorporated the Element-UI NavMenu component into my web application to create a navigation bar using Vue.JS with TypeScript. In order to achieve this, I have created a Vue component within a directory called "navBar," which contains the follow ...

What is the best way to effectively nest components with the Nebular UI Kit?

I'm currently facing an issue with nesting Nebular UI Kit components within my Angular app. Specifically, I am trying to nest a header component inside the home page component. The problem arises when the attributes take up the entire page by default, ...

Developing in Angular 2: Enhancing JSON data before passing it to the template

After receiving data from a JSON source, I have the following: { "name": "Leonardo", "weapon": "sword" }, { "name": "Donatello", "weapon": "stick" }, { "name": "Michelangelo", "weapon": "nunchucks" }, { "name": "Raphael", " ...