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

Flattening an array of Map in Typescript involves combining all the

I am working with an array containing entries of type Map<string, number> Is there a way to flatten this array into a single map? Map<string, number>[] converted to Map<string, number> Appreciate any help on this matter. ...

Issue with Angular application failing to fetch data from JSON server

I've been attempting to retrieve data from a local server, but so far I'm not getting any results. The concept is to have a service handle the retrieval process and return an observable for any components in need of the data to subscribe to. dis ...

Unable to redirect to another page in React after 3 seconds, the function is not functioning as intended

const homeFunction = () => { const [redirect, setRedirect] = useState<boolean>(false); const [redirecting, setRedirecting] = useState<boolean>(false); const userContext = useContext(UserContext); useEffect(() => { const valu ...

Angular 6 - Separate whole numbers and decimal values to style them differently in CSS

Is there a way in Angular to format a price so that the cents/decimal part appears as a superscript? What would be the most effective approach in Angular to achieve this based on the initial setup below? export class PriceComponent implements OnInit { ...

IntelliJ is indicating a typescript error related to react-bootstrap-table-next

Working with react-bootstrap-table-next (also known as react-bootstrap-table2) has been causing a Typescript error in my IntelliJ environment, specifically on the validator field within my column definition. Despite trying various solutions, such as adding ...

Unable to execute function on Child Element

I am encountering an issue when trying to call a function on a child component. Whenever I try to invoke it by clicking, I always receive an error indicating that the function is undefined. Here is the code in my Parent component: import {MatTableCompone ...

Can you point me in the right direction for declaring the ImageObject format in Angular?

To create an Image Slider similar to the one shown here, I need to load images from a source. However, I'm unsure about where exactly in the file (possibly in the component.ts?) I should declare them: imageObject: Array<object> = [{ ...

In Angular2, the derived class can inherit decorators

Within my Angular application, I am utilizing the BaseComponent which has a specified template. My goal is to use this same template HTML in a component that extends the base one. However, I am aware that class inheritance in Angular2 only applies to cla ...

Why is Vite's hot reloading feature displaying unpredictable outcomes?

I have a unique setup consisting of Vite, Typescript, and Vue 3 SPA utilizing "script setup". This app is equipped with Urql to query data from a GraphQL endpoint. An interesting occurrence happens where the query results are only displayed after the comp ...

Loading only specific HTML list elements in segments

Within my Angular4 application, I am faced with a challenge involving a large list of li elements. The browser struggles to handle the thousands of li's being displayed when the user interacts with the ul element. This results in slow loading times an ...

Implementing NgRx state management to track and synchronize array updates

If you have multiple objects to add in ngrx state, how can you ensure they are all captured and kept in sync? For example, what if one user is associated with more than one task? Currently, when all tasks are returned, the store is updated twice. However, ...

substitute one item with a different item

I am facing an issue with updating the address object within an organization object. I receive values from a form that I want to use to update the address object. However, when I try to change the address object in the organization using Object.assign, i ...

Angular 2 failing to recognize service variable changes initiated from component

Hello there, I'm currently facing a challenge with updating my component to reflect the correct value of a service variable whenever it changes. Here's what I have so far: Snippet from Component1 HTML {{icons | json}} Component1 Code icons: ...

The new PropTypes package is incompatible with TypeScript's React context functionality

When utilizing React.PropTypes, the code functions correctly but triggers a warning about deprecation (Accessing PropTypes via the main React package is deprecated...): import * as React from 'react'; export class BackButton extends React.Compo ...

Jasmine reported that there were no specifications found in the Angular project written in TypeScript

I'm facing a frustrating issue with Karma and Jasmine in my Angular 9 project. Despite setting up the configuration files correctly, I keep getting a "No specs found" message when running ng test. I have tried various adjustments, including creating d ...

How can I place an Object in front of an Array in JavaScript?

Currently, I am working on an Angular project where I need to modify a JSON array in order to display it as a tree structure. To achieve this, the objects in the array must be nested within another object. Desired format / output: this.nodes = [ { id ...

How to extract key-value pairs from an object in a TypeScript API request

I am trying to extract the data '"Cursed Body": "100.000%"' from this API response using TypeScript in order to display it on an HTML page. Can anyone help me figure out how to do this? API Response { "tier": &q ...

What is the method for setting autofocus to the first input element within a loop?

I am currently working on a loop to display inputs, and I would like to be able to add focus to the first input element when it is clicked. Does anyone have any suggestions on how I can select that first element and set autofocus on it? ...

The successful loading of tab favicons in the DOM of an angular chrome extension is a triumph, however, explicit XHR requests are unfortunately

I've been immersed in developing a Chrome extension with Angular 5. Successfully, I managed to extract favIconUrls from the tabs API and link them to my popup.html's DOM. The icons are retrieved and displayed without any hiccups. See an example ...

Difficulties in Networking Requests Following Event Emitter Notification in an Angular Application

Within my Angular application, a network request is sent to retrieve filtered data based on user-selected filters. The function responsible for handling the filter values and executing the request is outlined as follows: public onFilterReceived(values) { ...