Issue with maintaining variable state in Angular 7 service component

I currently have 2 components and a single service file in my Angular project, which consist of a login component and a dashboard component.

The issue arises when I try to access the user data from the service file. In the login component, the user data is retrieved successfully using this.userService.user. However, upon routing to the dashboard component and trying to log the same user data with this.userService.user, it appears as undefined.

import { Component, OnInit } from "@angular/core";
import { RouterExtensions } from "nativescript-angular/router";
import { UserService } from "../../shared/services.module";

@Component({
    selector: "login",
    moduleId: module.id,
    templateUrl: "./login.component.html",
    styleUrls: ["./login.css"],
})
export class LoginComponent implements OnInit {
    email: string;
    password: string;

    constructor(private router: RouterExtensions, private userService: UserService) { }

    signUp() {
      this.userService.login(this.email, this.password)
      .subscribe(res => {
          console.log(this.userService.user)
          this.router.navigate(["/dashboard"], { clearHistory: true, animated: false });
      });
    }

    ngOnInit(): void {
    }
}

Upon further exploration in the dashboard component, the same issue occurs where this.userService.user remains undefined.

import { Component, OnInit, Input } from "@angular/core";
import { RouterExtensions } from "nativescript-angular/router";
import { UserService } from "../../shared/services.module";

@Component({
    selector: "dashboard",
    moduleId: module.id,
    templateUrl: "./dashboard.component.html",
    styleUrls: ["./dashboard.css"],
})
export class DashboardComponent implements OnInit {
    constructor(private router: RouterExtensions, private userService: UserService) {
   }

    ngOnInit(): void {
      console.log(this.userService.user)
      console.log(this.userService.getUserName())
    }
}

This issue also persists even when utilizing the helper function getUserName solely to return the name in the service file.

If you have any insights or suggestions on why this unexpected behavior is occurring and how to address it, your assistance would be greatly valued. Thank you.

Answer №1

Here is a solution for you:

If you are providing a service within a module

@NgModule({
    imports: [
        ...
    ],
    declarations: [
        ...
    ],
    providers: [
        ... // If you have the service you want to provide globally here, remove it
    ]
})
export class YourModule {
    static forRoot(): ModuleWithProviders {
        return {
            ngModule: YourModule, // This module's name
            providers: [ YourService ] // Include the service you want to provide globally here
        };
    }
}

In your app.module.ts file

@NgModule({
    declarations: [
        AppComponent,
        ...
    ],
    imports: [
        ...
        YourModule.forRoot() // Add this line
    ],
    providers: [
        ...
    ],
    bootstrap: [ 
        AppComponent 
    ]
})
export class AppModule {
}

Your global service

@Injectable() // Remove "providedIn: ..." if present
export class YourService {
    ...
}

Components

@Component({
    selector: "dashboard",
    moduleId: module.id, // Remove this line
    templateUrl: "./dashboard.component.html",
    styleUrls: ["./dashboard.css"],
})
export class DashboardComponent implements OnInit {
     ...
}

Lastly, make sure to import YourModule into the imports of the module where you need to use YourService.

Answer №2

Upon my understanding, when you define it in this manner

@Injectable({providedIn:'root'})

it becomes accessible throughout the entire 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

Utilizing HTML imports in Typescript for efficient use as TemplateStringLiteral

Recently, I started using TypeScript for the first time and I'm looking to integrate it into my webpack build. Currently, I am working with ts-loader and babel-loader to load TypeScript files while also attempting to include HTML files within the scr ...

Toggle the Visibility of your Password

I am currently working on implementing a TypeScript function in my webpage to enable the toggling of password visibility using an icon. The desired functionality is as follows: when a button (in this case, a clickable icon) is pressed, the icon should chan ...

Export an array of objects using the Angular XLSX library

Here is my example data: exampleData: any[] = [ { "id": "123", "requestType": "Demo", "requestDate": "12/05/21", "status": "Success", "product": [ { "productName": "example product A", "productQty": "8" ...

Utilize ngrx/store to capture events from various components within an Angular application

Is there a way to utilize ngrx store in Angular to capture events from a grandchild component without relying on a service, Behavior Subject, or @Output? ...

Issues with eventEmitter functionality in Angular 2

Everyone performed admirably following the manual, here is the code snippet for WebSocketBroadcaster: import {EventEmitter, Injectable} from "@angular/core"; @Injectable() export class WebSocketBroadcaster { ee: EventEmitter<any> = new EventEmi ...

What steps do I need to take to activate the legacy policy API for Google login?

The Legacy People API has not been utilized in project 145315848075 or it is currently disabled. To enable it, please go to and then attempt again. If you have recently activated this API, please wait a few minutes for the changes to take effect before ...

What sets Interface apart from InstanceType<typeof Class> when used as a variable type?

Let's take a look at an example implementation: HttpService.ts: export interface IHttpService { request(): Promise<any>; formPostRequest(): any; } export class HttpService implements IHttpService { public async request() { // Implem ...

Typescript best practice: limiting global variables per file

I found it very useful in jslint to require declaring all used globals at the beginning of a file using the following syntax: /*global console, document */ Is there a similar feature available in Typescript? I managed to disable the implicit availabilit ...

The process of implementing ngOninit with asynchronous data involves handling data that may take

Within the ngOnInit method, I am calling a service method and assigning the return value to a member variable. However, when trying to access this variable later in the ngOnInit again, it seems that due to synchronization issues, the value has not been ass ...

Exploring Angular's APP_INITIALIZER: Comparing Promises and Observables

I have implemented an Angular v4 application where I need to retrieve settings from the server before the app starts. This is achieved using the APP_INITIALIZER: { provide: APP_INITIALIZER, useFactory: initializeSettings, deps: [SettingsService], ...

(NG2-CHARTS) Unable to connect to the Chart Type as it is not recognized as a valid property for binding

I encountered an issue with my Chart Component where I am seeing the error message below. I have successfully imported ChartsModule into my app.module.ts file, but I am unsure why this error is occurring? Can't bind to 'ChartType' since ...

What's the best way to use the keyboard's enter key to mark my to-do list

I'm looking to update my todo list functionality so that pressing enter adds a new todo item, instead of having to click the button. <h1 style="text-align:center">Todo List</h1> <div class="container"> ...

Error: The script "build:universal" is required but not found in the

I encountered errors while attempting to run my Angular application on the server side: npm ERR! missing script: build:universal npm ERR! A complete log of this run can be found in: npm ERR! /home/training/.npm/_logs/2018-10-03T11_50_40_593Z-debug.lo ...

Getting around using Material-UI Icons

Is it possible to utilize a Material-UI Icon for navigation using React Router Dom? I attempted the following approach without success: <NavigateBeforeIcon path="/vehicles"></NavigateBeforeIcon> With buttons, I am able to use component={Link ...

What are some ways to enhance this TypeScript code using Functional Programming with the FP-TS library?

i am struggling to write some typescript code using fp-ts Below are the tasks that i want the algorithm to carry out: Once a path is received from the command line, it should check if the given path exists search for all files in the directory and locat ...

How to extract a type from a nested type using TypeScript

I am trying to define a type structure where both a and foo are optional: type Something = { a?: { foo?: { bar: { c: { id: string, countryCode: number, animal: { ... } } } } } } Now I n ...

Determine if a condition is met in Firebase Observable using scan() and return the

Within Firebase, I have objects for articles structured like this: articles UNIQUE_KEY title: 'Some title' validUntil: '2017-09-29T21:00:00.000Z' UNIQUE_KEY title: 'Other title' validUntil: '2017-10-29T21:00:00 ...

Steps to prevent subfolder imports in my npm package

My npm package is built using: typescript webpack webpack.config: {... entry: './src/index.ts } library tree: - package.json - src - - index.ts - - ...all_my_code... I have all my library functionality and types exported from the index.ts file. T ...

Retrieve specific files from a Firestore collection based on a particular field

I am currently working on a web application using Angular 6 and angularfire2. I have successfully retrieved all documents in a collection, but now I need to filter those documents to only get the ones with the field role.moderator == true. private users ...

Tips for Using Typescript Instance Fields to Prevent Undefined Values

After creating a few Typescript classes, I encountered an issue where I would get an undefined error when trying to use them after instantiating. I experimented with initializing my fields in the constructor, which resolved the problem, but I don't t ...