Event emitters from Angular 4 are failing to receive emitted events after the page is refreshed

Hey there, I'm facing an unusual issue with event emitters not functioning correctly during page refreshes.

Here's the scenario: First, the user lands on the login page. Upon successful login, they are directed to the home page where I need specific data to be displayed in header.component.html fetched from home.component.ts

The components involved are:

app.component.html

<app-layout-header></app-layout-header>
<router-outlet></router-outlet>
<app-layout-footer></app-layout-footer>

header.components.ts

@Component({
  selector: "app-layout-header",
  providers: [],
  templateUrl: "./header.component.html"
})
export class HeaderComponent implements OnInit {
  profile = {};

  constructor(
    private _authService: AuthService,
    private _clipboardService: ClipboardService
  ) {}

  ngOnInit() {
    this._clipboardService.myProfileDataEvent.subscribe(data => {
      this.profile = data;
      console.log("data changes");
    });
  }

  ngOnDestroy() {
    // prevent memory leak when component is destroyed
    this._clipboardService.myProfileDataEvent.unsubscribe();
  }

  logout() {
    this._authService.logout();
  }
}

clipboard.service.ts

@Injectable()
export class ClipboardService {
  @Output() myProfileDataEvent: EventEmitter<any> = new EventEmitter();

  constructor() {
    this.myProfileDataEvent.emit({Name:'Siraj'})
  }

  setProfileData(data: any) {
    console.log("emitting events");
    return this.myProfileDataEvent.emit(data);
  }

}

In home.component.ts, I am making an API call and updating the profile data by calling

this._clipboardService.setProfileData(response.json().payload.Profile)

home.component.ts

 ngOnInit() {
    this._authService.checkLogin();
    this._profileService.getHomeData()
      .subscribe(response => {
       this._clipboardService.setProfileData(response.json().payload.Profile)
        },
        err => {
          alert('home data error');
        });
  }

Everything works fine if I navigate to the home page after logging in. However, if I refresh the page after logging in, the emitted event is not received in header.component.ts

Any assistance would be highly appreciated. Thank you!

Answer №1

In my opinion, I found that the onInit function of HeaderComponent is more effective when called in the constructor rather than after testing it. It appears that subscribing to the Event Emitter should be done prior to onInit.

Although I attempted to refactor your code, I encountered some challenges along the way.

Interactive Demo Here

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

What steps are involved in adding a table footer to ng2-smart-table?

I'm currently incorporating ng2-smart-table into my application. I am looking to include a table footer below the table to provide additional information such as Sum Amount, Discount Amount, and more. Below is an example of my code in a TypeScript fi ...

Traverse a tree structure of nested child objects in an Angular template using a JavaScript

Check out the Javascript object below: { "id": "1554038371930_ajhnms9ft", "name": "CPS", "nodes": [ { "id": "1554038905938_le34li2cg", "name": "Consumer Journey", "nodes": [ { ...

Vue: Simple ways to retrieve state data in MutationAction

I'm having trouble accessing the state inside @MutationAction Here is the setup I am using: Nuxt.js v2.13.3 "vuex-module-decorators": "^0.17.0" import { Module, VuexModule, MutationAction } from 'vuex-module-decorators' ...

In Visual Studio, the .js.map files and .js files seem to be mysteriously hidden, leaving only the TypeScript .ts files visible

In the past, I utilized Visual Studio Code for Angular 2 development and had the ability to hide .js and .js.map files from the IDE. Now, I am working on a project using VS 2017 Professional with Typescript, Jasmine, Karma, and Angular 4. Task Runner, etc. ...

Utilize the UserService in NestJs to enhance security within the RolesGuard functionality

In my application, I have a module called UserModule that exports the UserService. Here is an example of how it is done: @Module({ imports: [ MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]), MongooseModule.forFeature([{ name: ...

Ensuring correct association of values to avoid redundancies

There are 5 fields available for users to fill out on this form: Leave Code, From Date, Input Time1, To Date, and Input Time2. These variables are declared as a dates object in the .ts file, as shown below. interface Supervisor { name: string; code: s ...

Angular: accessing public properties

I have a component called "user.service.ts" that I want to share. import { Injectable } from '@angular/core'; import { Http, Headers, RequestOptions, Response } from '@angular/http'; import { AppConfig } from '../app.config&apos ...

The function RegisterOnChange is not a valid function

I utilized FormBuilder(fb) to create this form. this.serviceRecordForm = this.fb.group({ client: [], serviceRecordItem: this.fb.group({ productStatus: [''], password: [''], hasBackup: ...

Steps to resolve the issue of being unable to destructure property temperatureData from 'undefined' or 'null' in a React application without using a class component

CODE: const { temperatureData } = state; return ( <> <div className="flex flex-row"> {temperatureData.map((item, i) => ( <div className="flex flex-auto rounded justify-center items-center te ...

Discovering the bottom scroll position in an Angular application

I am working on implementing two buttons on an Angular web page that allow the user to quickly scroll to the top and bottom of the page. However, I want to address a scenario where if the user is already at the very top of the page, the "move up" button sh ...

`Creating the perfect bar``

Currently working on my resume using Angular and I am interested in incorporating a visual representation of my skill level in specific subjects. Came across something that caught my eye here: The challenge now is figuring out what exactly to search for i ...

Retrieving Information from a JSON Object using Angular 2

I'm dealing with a JSON object response. The object looks like this: {auth_token: "60a483bc0b1bc4dc0231ff0b90a67be1dad6ef45"} auth_token:"60a483bc0b1bc4dc0231ff0b90a67be1dad6ef45" proto : Object My goal is to extract the value "60a483bc0b1bc4dc0231f ...

How to Determine the Requirement Status of Input Variables in an Angular 2 Directive?

Is it possible to specify an input variable in a directive as required or optionally as non-required? In the example below, we have set a default value of false. However, if I fail to declare it in the parent component template, ng2 AoT throws an error: ...

Determining the specific condition that failed in a series of condition checks within a TypeScript script

I am currently trying to determine which specific condition has failed in a set of multiple conditions. If one does fail, I want to identify it. What would be the best solution for achieving this? Here is the code snippet that I am using: const multiCondi ...

Union does not contain the specified property in Typescript

Here are the types that I have: Foo { foobar: any } Bar { fooBarBar: any; } I want to use a function defined like this: this.api.submit(param: Foo | Bar) When trying to use it, I encountered an issue: this.api.submit(param.foobar) // does no ...

Personalized style for text overflow property

The application is created using Angular. Within a component, we have a div containing some text: <div>abcdefghijklmnop<div> Depending on the screen size, the text should either be fully displayed or clipped. I discovered the property 'te ...

Working with arrays in Angular 4 to include new items

I am struggling with the code below: export class FormComponent implements OnInit { name: string; empoloyeeID : number; empList: Array<{name: string, empoloyeeID: number}> = []; constructor() { } ngOnInit() { } onEmpCreate(){ conso ...

The Typescript compiler is throwing an error in a JavaScript file, stating that "type aliases can only be used in a .ts file."

After transitioning a react js project to react js with typescript, I made sure to move all the code to the typescript react app and added types for every necessary library. In this process, I encountered an issue with a file called HeatLayer.js, which is ...

having difficulties with angular subscribing to an observable

I am currently working on a service that retrieves a post from a JSON file containing an array of posts. I already have a service in place that uses HttpClient to return the contents of a JSON file. The main objective is to display the full content of the ...

Tips on displaying a spinner only when data is retrieved from an Http service

How can I ensure that a spinner is only shown during an HTTP service call and dismissed when my component receives data? To address this issue, I implemented a cache service to store data fetched from the HTTP service for future use. However, I want to sh ...