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

Tips for showing nested array values in Angular 8

I'm new to using angular and I'm attempting to display values from an array within another array in a table format. Here is my JSON array that I'd like to display in rows: { "data": { "Influencer": [ { ...

Store the beginning and ending times in a MySQL database using Sequelize and Node.js

I am currently developing a project management application where I need to keep track of the start and stop time for user work. To achieve this, I have implemented two buttons in the UI - START and STOP. When a user clicks the START button, the following ...

Steps for retrieving user timezone offset and transmitting it to the server in an ASP.net application

I need assistance with capturing and sending a user's timezone or offset when they successfully sign in. I came across the "getTimezoneOffset" method in JavaScript, but I'm unsure how to automatically send this data without the user explicitly in ...

Deciphering JSON data within AngularJS

When I retrieve JSON data in my controller using $http.get, it looks like this: $http.get('http://webapp-app4car.rhcloud.com/product/feed.json').success(function(data) The retrieved data is in JSON format and I need to access the value correspo ...

Is it possible to implement jQuery events on all elements belonging to a specific class

Hey there, I'm facing a little challenge with my code. Currently, I have a snippet that allows a user using iOS to drag around a <div> with the class .drag on the webpage. Everything works perfectly when there's only one instance of .drag, ...

jquery-powered scrollable content container

<script language="javascript"> $(document).ready(function($) { var methods = { init: function(options) { this.children(':first').stop(); this.marquee('play'); }, play: function( ...

Unfulfilled commitment on bcrypt

I am currently facing an issue while trying to validate a user's password using bcryptjs. I have implemented a function that returns a Promise, but I am encountering an error when reaching the bycrypt.hash step - all I see is Promise { <pending> ...

Leveraging external JavaScript libraries in SAPUI5

I'm currently facing an issue while trying to include an external .js file in my SAPUI5 Controller. jQuery.sap.includeScript("externalLibrary.min.js", function() { // initializing objects from the library }); Despite setting up ...

Having issues with Thymeleaf template not functioning properly when using inline JavaScript

I've encountered an issue when attempting to extract my function into a script within HTML. When written as shown below, it works perfectly: <input type="text" id="myInput" onkeypress="return confirm('Are you sure you want to delete ...

Troubleshooting problems with jQuery Chosen plugin post-AJAX request

I'm encountering an issue with the plugin called jquery-chosen not applying to a control that is reconstructed by an ajax call. Despite exploring other suggestions, I have yet to find a solution that works. The versions of jquery and jquery-chosen be ...

Tips for efficiently implementing AJAX requests for multiple forms within a single webpage

Previously, I had a form where clicking submit would hide the form and display the result on a div with classname=dig. However, after adding more forms, all the forms started submitting at the same time instead of individually. How can I fix this issue in ...

Try out Playwright for testing Angular form controls

I'm currently examining a form control using the Playwright framework. The structure of the DOM is as follows: <div class="form-group"> <label for="usernameInput">User name</label> <input type="text" ...

Enhancing Bootstrap modals with dynamic content and integrating Ajax for dynamic data retrieval in Laravel

I am facing some challenges while coding in Laravel, specifically with passing data to a modal (using the Bootstrap framework) and sending data to an Ajax post request. I have an array of items with an 'id', a 'name', and 'content& ...

Show different JSON data based on the existence of another key in Javascript

Having recently started learning JavaScript, I attempted the code below but couldn't quite get it to work. Despite consulting various resources, I still wasn't successful. Desired Output: To check if AUTO damage is present in the data. If so, re ...

Ways to conceal one message within another

I am currently working on incorporating Facebook's comments box into my website. My goal is to have the comments that I retrieve through GET requests and display in the template remain invisible to users, but visible to search engines. As part of an ...

Utilize PHP's file_get_contents to trigger the Google Analytics tracking pixel

For certain goals I have set up in Google Analytics, I am unable to use the JavaScript tracking. Instead, I am interested in achieving the same result by making a call with PHP. One solution that seems straightforward to me is to invoke the URL of the tra ...

Is there a way to append the current path to a link that leads to another URL?

I am currently in the process of separating a website, with the English version being on the subdomain en. and the French version residing on the www. Before making this change, I have a drop-down menu that allows users to select their preferred language ...

Having an issue where the Jquery clone function is only duplicating the content once. Looking to

I'm currently working on existing HTML table code. My goal is to copy the text from the 'th' header rows and paste them inside the corresponding td cells for each subsequent row. While I have successfully managed to copy the header row, it o ...

Show a dropdown menu based on a certain condition in Angular

Is there a way to conditionally display select options like this? <select id="updateType" class="form-control" formControlName="updateType"> <option value="personalDetails">Personal</option> <option value="addressD ...

Looking to extract data from various checkbox options and save it as an array variable

For a coding boot camp assignment, I'm working on a modal that includes options for the days of the week. My approach involves using Jquery .each and CSS :checked to retrieve the values assigned to each input. However, every time I attempt to log the ...