Angular Observable returning null results

After spending some time on this issue, I am still puzzled as to why I am consistently receiving an empty observable.

Service:

import { Injectable } from '@angular/core';
import { WebApiService } from './web-api-service';
import { BehaviorSubject, Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  private currentUserName: Subject<any> = new BehaviorSubject<any>({});
  private currentUser: Subject<any> = new BehaviorSubject<any>({});

  constructor(private webApi: WebApiService) { }

  setCurrentUsername(username) {
    this.currentUserName.next(username);
  }

  setCurrentUser(user) {
    this.webApi.GetMenuItems(JSON.stringify(user)).subscribe(response => {
      if (response !== []) {
        let res = response.d.replace(/\n|\r/g, ""); //eliminate new line and return characters
        res = JSON.stringify(eval("(" + res + ")")); //convert string to valid json
        res = JSON.parse(res); //convert to javascript object
        this.currentUser.next(res); //store object
      }
    });
  }
  
  get username() {
    return this.currentUserName.asObservable();
  }

  get user() {
    return this.currentUser.asObservable();
  }
}

Home Component:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { ColorGeneratorService } from '../../services/color-generator.service';
import { AuthService } from '../../services/auth.service';
import { Subscription } from 'rxjs';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-home-page',
  templateUrl: './home-page.component.html',
  styleUrls: ['./home-page.component.scss']
})
export class HomePageComponent implements OnInit, OnDestroy {

  user: Subscription;
  username: string ;

  roleArray: Array<any>

  constructor(private auth: AuthService, private route: ActivatedRoute) { }

  ngOnInit() {
    this.username = this.route.snapshot.paramMap.get('username');

    this.auth.setCurrentUsername(this.username);
    this.auth.setCurrentUser({ username: this.username });
    
    this.user = this.auth.user.subscribe(user => { 
      this.roleArray = user.roles;
    }); 
  }
}

Secondary Component:

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../services/auth.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-subject-page',
  templateUrl: './subject-page.component.html',
  styleUrls: ['./subject-page.component.scss']
})
export class SubjectPageComponent implements OnInit {

  user: Subscription;
  username: string;

  constructor(private auth: AuthService) { }

  ngOnInit() {
    this.user = this.auth.user.subscribe(user => { 
      console.log(user);
    }); 
  }
}

Upon further investigation, the Home Component successfully "sets" the user in the auth service, with a button that navigates to the subject-page component. However, upon clicking the button and transitioning to the subject-page component, the console.log only shows an empty object {} implying that the user information was not retained. You can view a Stackblitz example of the issue here.

Answer №1

Upon further investigation, it came to my attention that in my template file I had mistakenly implemented the standard

<a href="/some-link">Click Me</a>
instead of the correct syntax
<a routerLink="/some-link">Click Me</a>
. This innocent mistake led to a complete page and Angular app reload, resulting in the user observable value being reset to an empty object {}

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

The element is inherently an 'any' type as the expression of type 'number' does not have the capability to index type 'Object'

Hey there, I'm currently in the process of learning Angular and following along with the Note Mates tutorial on YouTube. However, I've hit a stumbling block as I attempt to implement sorting by relevancy. The issue lies with the code snippet belo ...

Navigating through Angular components can sometimes pose challenges in component routing

I have set up child component routing within my application. I am facing issues when trying to navigate to the default route using routerLink. Since the parent path includes ':id', the child routes only work when prefixed with ':id' ...

Tips for preserving data in Angular form fields

Within my angular application, a scenario exists where two pages are involved. On the initial page, users input data into a form and proceed by clicking "continue" which leads them to the subsequent page. The following page features a back button that ena ...

Using Boolean functions in ngStyle allows for dynamic styling of elements in Angular templates

<div *ngFor= “ let singleorder of order.order”> <p [ngStyle]=" 'color':(singleorder.status === 'CONFIRM' )? 'green' : 'red' , 'background' : (singleorder.status === ' ...

Issue encountered while generating menu using Angular's Material framework

In my Angular project, I am working on creating a right-side menu with specific functionalities. While the Home and Photo menus work perfectly, I am encountering an issue with the Admin menu. I intend to have 2 submenus open when clicking on the Admin tab, ...

Creating a checklist using HTML and CSS can be achieved by utilizing the <span> element and

I'm having trouble changing the color of a span box to red when I focus on a link. The span successfully changes color when activated, but nothing happens when I try to use the 'focus' pseudo-class. On click, different categories will displa ...

Finding the index of an element in an array using the filter method in Angular JavaScript

As I was working with an array of pages in a book, I wanted to find the index of a specific page that had been identified using filter. While my current function gets the job done, I can't help but wonder if there's a way to combine indexOf or fi ...

Finding the location of a file within a published web component

I am currently working on a webcomponent where I need to include a link tag in the head section and set the href attribute to a folder within a node module. At this stage, during the development of my component, my project structure looks like this: http ...

Weekday Filter in Angular 2

Looking to utilize the date pipe feature in Angular 2, specifically aiming for output that only includes the weekday name, such as "Wednesday." I am aware of the typical method to achieve this: {{ strDate | date :'fullDate' }} This would resul ...

Troubleshooting "jest + enzyme + react16: The src attribute of <img> tag is not sending

Currently, I am utilizing jest along with enzyme for testing my react component titled "AnimateImage". This component includes an image element within it: import * as React from 'react'; import { PureComponent } from 'react'; interfac ...

Angular Material Slide-Toggle Takes Too Long to React

In my project, I am facing an issue with a control panel that contains an Angular Mat-Slide-Toggle element. Here is the code snippet: <mat-slide-toggle (change)="onQAStateDisplayChanged($event)">Display QA Status</mat-slide-toggle> When the c ...

Troubleshooting Jasmine Unit Testing issues with the ng-select library

Recently, I integrated the ng-select component from Github into my Angular application without encountering any console errors during runtime. It functions as expected; however, issues arise when running unit tests with Jasmine. To incorporate NgSelectMod ...

Send empty object using FormBuilder

When retrieving an object from a backend API service like this: data: {firstName:'pepe',lastName:'test', address = {street: 'Cervantes', city:'Villajoyosa'} } or data: {firstName:'pepe',lastName:'test ...

What is the most effective approach for revealing AngularJS controller methods in TypeScript?

I have been exploring a way to attach the controller object to the scope in a different manner. Here is an example of how it can be achieved. interface IAppCtrlScope extends ng.IScope { info: any; } class InfoCtrl { header: string; name: strin ...

The ngb-datepicker feature seems to be experiencing issues when used within an Angular Material input field (

How can I integrate ngb-datepicker into a material Input? While I have successfully applied the datepicker to the mat input, I am facing an issue with the month and year dropdowns. I attempted the following snippet : <mat-form-field> <input matI ...

Using React's Ref to handle conditional rendering and handling the case when

I am facing an issue with my React ref animationRef being null when I conditionally render an element. It works perfectly fine outside of the condition, but not within it. Is there a way to ensure that the ref has a value even when conditionally renderin ...

Obtaining RouteParams in the loader function of RouteConfig can be achieved by following a

Is there a way to achieve the following setup: @RouteConfig([ { path: '/example/:name', name: 'Example', loader: (params: RouteParams) => { let name = params.get('name'); return _EXAM ...

The parameter type 'Object' cannot be assigned to the parameter type 'JSON' in the HttpClient GET method

Hey there! Currently, I'm deep into developing an Angular 6 + Flask application and I've encountered a bit of a snag: Error TS2345: Argument of type 'Object' is not assignable to parameter of type 'JSON'. This issue arises w ...

utilize the getStaticProps function within the specified component

I recently started a project using Next.js and TypeScript. I have a main component that is called in the index.js page, where I use the getStaticProps function. However, when I log the prop object returned by getStaticProps in my main component, it shows a ...

What is the way to obtain loading start/end events while using a loader widget in conjunction with an asynchronous Firebase request (observable)?

I have implemented AngularFire in the following manner: constructor(private afDb: AngularFireDatabase) { allRRs$ = this.afDb.list(`research_reports-published/`).valueChanges(); } The variable allRRs$ is an observable that I am utilizing in my templat ...