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.