Angular 6 Component Communication Service ensuring seamless data exchange between two components

Hey everyone, I'm currently facing a challenge with Angular 6 and its components. I've created a service to facilitate communication between two components - triggering an event in one component should reload the other.

Here is the code for the CommunicationService:

import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject} from 'rxjs';

@Injectable()
export class CommunicationService {

private subject = new BehaviorSubject<boolean>(false);

constructor() { }

public change(){
  this.subject.next(true);
}

public getChange(): Observable<boolean>{
  return this.subject.asObservable();
 }

}

Next, here is the code for the Observable component:

public subscription: Subscription;

constructor(
private _router: Router,
private _communication: CommunicationService
){}

loginUser()
{
  this._router.navigate(['./loginUser']);
  this.subscription= Observable.interval(500).subscribe(x=> 
  {
   this._communication.getChange().subscribe( resp=>{
    if(resp===true){
        this.ngOnInit();
        this.subscription.unsubscribe();
    }
  })
});

  }

Finally, take a look at the trigger component code:

this._communication.change();

In essence, the last component imports the Communication Service and calls the method change(). While debugging the code, everything appears correct but I always receive false as the response of the subscription, even when the change() method is called. What am I doing wrong?

UPDATE - ISSUE RESOLVED: Initially, my code was correct. The issue stemmed from incorrectly importing the service in both components within providers instead of importing it in the app module. It's now functioning properly.

Answer №1

Providing a service

private status = new BehaviorSubject(false);
  currentStatus = this.status.asObservable();

  constructor() { }

  public updateStatus(flag: boolean) {
    this.status.next(flag)
   }

Service Component:

loginUser()
  {
    this._router.navigate(['./loginUser']);
    this.subscription= Observable.interval(500).subscribe(x=> 
    {
     this._communication.currentStatus.subscribe( response =>{
      if(response === true){
          this.ngOnInit();
          this.subscription.unsubscribe();
      }
    })
  });

  }

Action Trigger:

this._communication.updateStatus(true);

Answer №2

After making a few adjustments, the code now looks like this:

Service:

private subject = new BehaviorSubject(false);
currentSubject = this.subject.asObservable();

constructor() { }

public change(flag: boolean) {
  this.subject.next(flag);
}

Component listening with an interval of 0.5:

loginUser()
{
  this._router.navigate(['./loginUser']);
  this.subscription = Observable.interval(500).subscribe(x => {
    this._communication.currentSubject.subscribe(resp => {
      if (resp === true) {
        this.ngOnInit();
        this.subscription.unsubscribe();
      }
    })
  });

}

Trigger:

public onSubmit(){
  this._userService.signup(this.userAux, 'true').subscribe(
    resp2 => {
      this.token = resp2.token;
      if (this.token.length <= 0) {
        alert('Token has not been generated');
      } else {
        localStorage.setItem('token', this.token);
        this._communication.change(true);
        this._router.navigate(['./']);
      }
    },
    err => {
      const errorMessage = <any>err;
      if (errorMessage != null) {
        const body = JSON.parse(err._body);
        this.errorMessage = body.message;
      }
    }
}

The response is always false, the flow of execution starts with loginUser() listening every 0.5 seconds by subscribing to the Observable Object, then the component trigger calls change(), but the value remains false for Observable.interval to keep listening.

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

When attempting to replace the outdated Angular 2 router with the new Router, I encountered an error

I have the main app component and I want to add subroutes under the admin component like /admin/users, /admin/subscribers @Component({ selector: 'my-app', template: `<router-outlet></router-outlet>` directives: [ROUTER_DI ...

Issue in Angular 2: HttpClient provider not found during Karma-Jasmine Testing

I am encountering an error in my karma test that states there is no provider for Http, even though my application is running smoothly without any errors. I have imported import { HttpModule } from '@angular/http'; in my app.module.ts file and add ...

Eliminate white spaces in Angular 2 URLs

When passing the name and ID of a product in my URL, the space between the product names is creating "%20" characters. An example of my current URL: detail/Cardon%20Black%20Rectangular%20Eyeglasses/588319df247d4b6e3397a6fa How can I remove these "%20" t ...

:host-selector for Angular Material dialog

I am currently working with a dialog component provided by angular-material and I need to customize the appearance of the popup dialog. I am aware that there is some support for styling through the component generation: let dialogRef = dialog.open(MyDi ...

The boolean validation function appears to be malfunctioning in the NodeJS environment

I am currently working on developing the node js API and I am fetching data using a URL query. get_posts_default?pageId=ge4JqBn9F0srzHnVFHmh&asking_post=false&asking_responce=false&maxSort=-1&minSort=-1&limit=20 This function is respo ...

The UI elements are failing to reflect the changes in the data

In an attempt to establish communication between three components on a webpage using a data service, I have a Create/Edit component for adding events, a "next events" component for accepting/declining events, and a Calendar component for displaying upcomin ...

A guide to creating a TypeScript redux middleware class

As specified in the typescript definition for Redux, these interfaces must be implemented to create middleware: /* middleware */ export interface MiddlewareAPI<D extends Dispatch = Dispatch, S = any> { dispatch: D getState(): S } /** * A midd ...

Updating ng-bootstrap to be compatible with Bootstrap 3.3.7 by downgrading from version 4.3.1

I have an Angular 6 project with Bootstrap 4 and ng-bootstrap for modal dialogs. However, I need to integrate this into another project which is using Angular 3.3.7. As a result, I was required to downgrade the version of Bootstrap. Here are the steps I fo ...

Creating a null array of a specific size can easily be accomplished in Typescript

When I use the splice method to add elements to an array at a specified index, I find myself creating a null array first in order to achieve this. If I use an empty array instead, the elements do not get pushed to the specific instance that I intended. Cur ...

What is the process for removing a cookie in the MEAN stack?

I am facing an issue with deleting a cookie from my Node API in my Angular client (MEAN stack). On the Node side, I have a controller and a router set up, while on Angular, I subscribe to the service. // node router authRouter.get('/logout', t ...

Encountering TypeScript error TS2769 when using Material UI's TableRow with a Link component

Currently, I am in the process of developing a React Single Page Application using Typescript and Material UI. One of my objectives is to include a table where each row acts as a clickable link. The Link component within this table is derived from React Ro ...

Type '{}' is lacking the subsequent attributes from type '(ColGroupDef | ColDef)[]': size, shift, unshift, join, and more than two dozen others

Currently, I am working on integrating AG-Grid into a TypeScript project with React. The main issue I am facing is related to two errors that my linter is detecting in the code where I utilize Column Definitions (columnDefs) and Row Data (rowData). The er ...

The 'items' property cannot be linked to 'virtual-scroller' as it is not a recognized attribute

I'm currently facing an issue with integrating virtual scroll into my Ionic 4 + Angular project. Previously, I relied on Ionic's implementation of virtual scroll (ion-virtual-scroll) which worked well initially. However, I encountered a major dr ...

What steps can be taken to ensure that storybook continues to build successfully despite TypeScript errors?

After configuring a CRA typescript template and integrating storybook into my app, I encountered an issue with Chakra-UI components lacking typescript support. When running 'yarn storybook', the app functions properly and serves up the component ...

Using Angular 2+ to make an http-get request with parameters

I am looking to create a GET method with multiple parameters. Currently, my example works with one parameter but I need to add another. In the backend code segment below, you can see where I am trying to pass the second parameter, 'created_by', b ...

What steps can I take to avoid unintentionally populating this object with undefined values?

This issue occurs when the variable level is initialized with the value 'undefined'. Although this code functions correctly in JavaScript, it encounters problems when using TypeScript. interface Find { level?: string; } let find: Find = {}; ...

Preserving quotation marks when utilizing JSON parsing

Whenever I try to search for an answer to this question, I am unable to find any relevant results. So please excuse me if this has been asked before in a different way. I want to preserve all quotation marks in my JSON when converting from a string. In m ...

Creating Instances of Variables Within a Class

Currently, I am working on a project using Ionic and Angular. I have come across various ways of instantiating variables and I'm unsure about the implications of each method. Here are three scenarios that confuse me: export class someClass { myVaria ...

A guide on utilizing useState with Typescript to declare and update an array of strings

I am facing an issue with the code below: interface ISTx { tx: Array<string>, setTx: any } const [tx, setTx] = useState<ISTx>([]) //Argument of type 'never[]' is not assignable to parameter of type 'ISTx setTx(oldArr ...

Tips on adjusting the quantity of items in your cart

I'm currently working on a shopping cart project where I need to implement functionality to increase or decrease the quantity of items. However, I've encountered an issue where nothing happens when I click on the buttons. <div class="car ...