Transferring information between two components in separate Angular 4 modules

Within my application, I have defined two modules named AppModule and UserModule.

I am currently encountering an issue with data sharing between the AppComponent and the LoginComponent (which belongs to the UserModule).

Below is a snippet of app.component.html:

<ul class="nav navbar-nav lg-nav visible-lg visible-md">
        <li><a routerLinkActive="nav-active" routerLink="/page1">page1</a></li>
        <li><a routerLinkActive="nav-active" *ngIf="!loggedIn" routerLink="/user/login">Login</a></li>

</ul>

Here is the implementation in app.component.ts:

    import { MessageService } from './services/message.service';
   export class AppComponent {
    loggedIn = false;
    constructor(private ms: MessageService, private cd: ChangeDetectorRef) {
      this.ms.getMessage().subscribe(data => {
      console.log('messageService: ', data);
      if (data === 'login') {
        this.loggedIn = !this.loggedIn;
        this.cd.detectChanges();
      }
    });
  }
}

Additionally, here is how login.component.ts is implemented within the UserModule:

    constructor(
     private ms: MessageService
    ) {}
    -> call to login service
    -> on success response
    this.ms.sendMessage('login');

Lastly, the message.service.ts functionality:

import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
@Injectable()
export class MessageService {
  private message = new Subject<any>();
  constructor() {}
  sendMessage(message) {
    this.message.next({ message: message });
  }
  clearMessage() {
    this.message.next();
  }
  getMessage() {
    return this.message.asObservable();
  }
}

The main issue lies in the fact that the observer is not being subscribed in app.component.ts. I attempted utilizing the MessageService in a shared module but without success. How can I ensure that the message sent from LoginComponent (UserModule) reaches AppComponent when a user logs in, causing the Login Button to disappear?

Answer №1

Avoid creating a new observable every time you invoke the getMessage function

import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
@Injectable()
export class MessageService {
  private message = new Subject<any>();
  private messageEvent$ = this.message.asObservable();
  constructor() {}
  sendMessage(message) {
    this.message.next({ message: message });
  }
  clearMessage() {
    this.message.next();
  }
  getMessage() {
    return this.messageEvent$;
  }
}

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

Using jQuery to load and parse a JSON file stored on a local system

I am a beginner in scripting languages and recently searched for ways to load and parse JSON files using jQuery. I found helpful resources on Stack Overflow. The JSON file I am working with is called new.json. { "a": [ {"name":"avc"}, ...

Show specific content based on which button is selected in HTML

I am working on a project where I have three buttons in HTML - orders, products, and supplier. The goal is to display different content based on which button the user clicks: orders, products, or supplier information. function showData(parameter){ i ...

Tips for swapping out text with a hyperlink using JavaScript

I need to create hyperlinks for certain words in my posts. I found a code snippet that does this: document.body.innerHTML = document.body.innerHTML.replace('Ronaldo', '<a href="www.ronaldo.com">Ronaldo</a>'); Whil ...

Transferring an object from the factory to the controller

I'm currently working on setting up a factory that sends an ajax request to an API and then returns a data object. Here is the code snippet I have written: app.factory('Test', function($http, $q) { var data = {response:{}}; var getM ...

How can I ensure that my text input and button are in sync in ReactJS?

I'm currently developing a basic search bar that reads input and updates the 'inputString' state when the content changes. Upon clicking the 'search' button, the inputString is split and assigned to the 'keywords' state a ...

Generate a unique ID each time the page is loaded or refreshed

I'm currently working on a function that will display a unique ID or a different video each time the page is loaded or refreshed. My main objective is to design a splash intro popup that features a <section> with a full-screen YouTube video bac ...

Why is my Vue list not showing the key values from a JavaScript object?

I am struggling to utilize a v-for directive in Vue.js to display the keys of a JavaScript object in a list. Initially, the object is empty but keys and values are populated based on an API call. Here's an example of the data structure (I used JSON.st ...

How to use jsZIP in angular to bundle several CSV files into a single zip folder for download

I have a code snippet below that demonstrates how to create data for a CSV file and download the CSV file in a zip folder: generateCSVfiles() { this.studentdata.forEach(function (student) { this.service.getStudentDetails(student.studentId).subsc ...

Memory leakage in Internet Explorer as a result of JavaScript code

Recently, I created a website that utilizes jquery ajax to send an ajax request every minute in order to retrieve json data. This data is then parsed and added into the DOM. While this process runs smoothly on Chrome and Firefox, I noticed a significant m ...

The Angular component template fails to reflect the current value received from the observable

I am facing an issue with a component that updates its state from a service observable: import {Component} from '@angular/core'; import {SessionTimeoutService} from "./session-timeout/session-timeout.service"; import {Observable} from & ...

Issue: "Access-Control-Allow-Origin does not allow origin null" error message is returned when attempting to access a PHP file using jQuery's ajax method with dataType text/html selected

Why am I encountering this issue in Chrome when using dataType text and HTML? It seems to work fine if I output JavaScript and set the dataType to script. How can I return non-JavaScript data from a PHP file? Client-side code: $.ajax({ url: ...

What is the best way to close ngx-simple-modal in angular7 when clicking outside of the modal component?

Can anyone help me with closing the modal in my angular7 app when the user clicks outside of the modal component? I have been using the ngx-simple-modal plugin, and I tried implementing the following code: this.SimpleModalService.addModal(LinkPopupCompone ...

Determine the number of occurrences of specific values within a group of objects based on a

I have the following dataset: const data2 = [ { App: "testa.com", Name: "TEST A", Category: "HR", Employees: 7 }, { App: "testd.com", Name: "TEST D", Category: "DevOps", Employee ...

Locate the class and execute the function on the existing page

Stepping outside of my comfort zone here and I'm pretty sure what I've come up with so far is totally off. Ajax is new to me and Google isn't making things any clearer, so I was hoping someone more knowledgeable could assist! Basically, I w ...

Prevent discrepancies between the outcome on the server and the client side

My website utilizes a combination of PHP and JavaScript for processing results - some server-side, some client-side. Solely relying on JavaScript can cause issues with search engine crawling, while using only PHP may not provide real-time responses accura ...

Selecting properties from a GeoJSON object on the fly with Leaflet

I am currently attempting to dynamically modify the displayed property on my leaflet map. Below is the code I have been working with: $("#button_thermal").click(function(){ $.getJSON("physicalProperties.geojson", function(data) { var geojson2 = L.geoJson( ...

What could be causing the continuous occurrence of the error message stating "Module 'socket.io' cannot be found"?

For the past few days, I've been attempting to incorporate socket.io into my NodeJS script. However, every time I run it, I encounter the frustrating error message stating "Cannot find module 'socket.io'". The detailed error is as follows: ...

Change the input field to uppercase using JavaScript but do not use inline JavaScript

Hey there! I have a basic script set up (see below) with an input field allowing users to enter a query. This query is then sent to a socrata webservice to request specific data, which is displayed in an alert box. So far, everything works smoothly. var l ...

Modifying background with JavaScript and AJAX技术

I currently have a table structured like the following; <table style="width: 100%; border: solid 1px #666600; min-width: 800px" cellpadding="0" cellspacing="0"> <tr> <td id="aaa">&nbsp;</td> ... Using jQuery's ajax functi ...

What is the best way to pass an email as a Laravel parameter within a function using Angular?

I'm currently working on a feature that allows users to delete their account only if the input field matches their email address. However, I encountered an error: Error: $parse:lexerr Lexer Error when attempting to set this up. Here is my HTML code: ...