ngOnInit unable to properly listen to event stream

I've been trying to solve a persistent issue without success. The problem involves the interaction between three key elements: the HeaderComponent, TabChangingService, and TabsComponent. Within the HeaderComponent, there are three buttons, each with a specific click method as shown below:

click(tab: number) {
    this.tabChangingService.changeTab(tab);
    this.router.navigate(['/tabs'])
}

Additionally, in the ngOnInit method of the TabsComponent, the following code is present:

ngOnInit() {
  this.tabChangingService.tab.pipe(
   tap(tab => this.tab = tab),
   tap(tab => console.log('setting tab ', tab) // added this linte
  ).subscribe();
}

The template contains the switch case for displaying content based on selected tabs:

<ng-container [ngSwitch]="tab">
  <div id="tab1" *ngSwitchCase="0">content...</div>
  <div id="tab2" *ngSwitchCase="1">content...</div>
</ng-container>

Furthermore, here is the code snippet from the TabChangingService:

export class TabChangingService {

  private _tab = new Subject<number>();

  constructor() {

  }

  public changeTab(tab: number) {
    console.log('Changing to tab ', tab); // added this line
    this._tab.next(tab);
  }

  public get tab() {
    return this._tab;
  }

}

The issue arises when clicking a button on the header – the tab does not get selected until the second click. This behavior could be attributed to the component's mounting delay upon first click. If you have any insights or suggestions, I would greatly appreciate your help. Thank you!

EDIT
Upon the first click on a header button, "Changing tab" is printed but "Setting tab" is absent until the second click.

Answer №1

Optimize with setTimeout

ngOnInit() {
  this.tabChangingService.tab.pipe(
   tap(tab => {
      setTimeout(()=>{   
        this.tab = tab
      }, 1);
   })
  ).subscribe();
}

Consider adjusting the timeout duration to troubleshoot any potential Component initialization problem.

Answer №2

For your tab-changing functionality, include the following in your service:

private _tab = new Subject<number>();
tabChanged = this._tab.asObservable();

In your component's ngOnInit() method, add the following:

ngOnInit() {
 this.tabChangingService.tabChanged.subscribe(
   // Add your code here.
 );

It's important to note whether there is a direct relationship between the components or not. However, utilizing a service should handle that aspect. Make sure to initialize your variable to Observable.

The code provided demonstrates my understanding of how Observables and Subjects work together. Feel free to correct any inaccuracies in my explanation above.

Answer №3

After following Sunil's suggestion, I managed to resolve the issue using a setTimeout. Interestingly, the setTimeout was implemented not in the TabsComponent, but rather in the HeaderComponent while emitting the selected value. Here is how it was done:

click(tab: number) {
 setTimeout(() => {
    this.tabChangingService.changeTab(tab);
   },
   500
 )
 // rest of the code
}

A big thank you to everyone for their assistance :D

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

Knexfile Doesn't Utilize TypeScript Paths

When attempting to run a migration, I encountered an issue with Knex. My Knexfile is in Typescript and uses path aliases from tsconfig.json. However, Knex is throwing an error stating Cannot find module '@foo-alias/bar-module'. What adjustments d ...

Upgrade of Angular 2 to rc 5 presents with unresolved peer dependencies

I am looking to update my angular version to rc5 in order to utilize NgModule. Following the directions provided by Angular 2. I have made changes to my package.json dependencies and then executed npm stall in the terminal: ... The results from the ter ...

Tips for activating automatic building of packages when utilizing pnpm install?

Our unique project is utilizing a combination of pnpm, workspace, and typescript in adherence to the monorepo standard. Upon cloning the repository, we execute a pnpm install command to download dependencies and establish links between local packages. De ...

Struggling to integrate D3.js with React using the useRef hook. Any suggestions on the proper approach?

I'm currently working on creating a line chart using d3.js and integrating it into React as a functional component with hooks. My approach involved utilizing useRef to initialize the elements as null and then setting them in the JSX. However, I encou ...

Running "ng lint --fix" does not automatically correct the issues in my files, but it does effectively pinpoint all the errors that need to be addressed

I am currently working on resolving lint issues present in files that are automatically generated through openapi-generator. Let's take a look at one of the files that needs fixing: https://i.sstatic.net/GDocT.png To address these errors, I have be ...

Why does Rollup insist on treating my dependency's TypeScript code as if it were written in JavaScript?

I've included an example code snippet here: https://github.com/thejohnfreeman/bugs/commit/b4ff15a670691ada024589693d22f4fd0abae08d The module called parent is primarily composed of type declarations written in TypeScript. The source entrypoint for Ty ...

Issue encountered in loading css and js folders during the build of the Angular2 application due to the files not being found

I have developed an Angular 2 application that utilizes Node.js server APIs. After building the app using nd b, the files were generated in the dist folder. Where should I specify the production URL for the build so that all CSS and JS files load properly? ...

I encountered an issue where I did not receive a response when utilizing res.write() within the fetch function

Currently, I am utilizing the <res.write()> method in nodejs at https://nodejs.org/api/http.html#responsewritechunk-encoding-callback. In addition to this, I am also implementing the fetch function which can be found at https://developer.mozilla.org/ ...

Encountering an issue where the Angular build is unable to locate the installed Font-Awesome node module

Every time I attempt to compile my project using ng build --prod, I encounter the following error: ERROR in ./src/styles.scss Module build failed: ModuleBuildError: Module build failed: Error: Can't resolve '~font-awesome/css/font-awesom ...

Updating Error: Unable to establish connection with IP address 104.16.21.35 on port 80; Error code: ECONNREFUSED. This issue is being handled by the _

I need help updating my Angular version from 5 to 6 and I'm following these steps: Want to upgrade project from Angular v5 to Angular v6 After running the commands ng update @angular/cli and ng update @angular/core, I encountered the err ...

What is the best way to utilize the features of component A within component B when they exist as separate entities

Component A has all the necessary functionalities, and I want to use it in Component B. The code for ComponentA.ts is extensive, but it's not written in a service. How can I utilize the logic from Component A without using a service, considering both ...

Guide on creating a generic type that depends on the arguments provided, specifically a union type

I am dealing with the following similar types: class ActionFoo { action: 'foo'; foo: string; } class ActionBar { action: 'bar'; bar: number; } In addition, I have some handler functions for each type of defined "action", such a ...

The RC-dock library's 'DockLayout' is not compatible with JSX components. The instance type 'DockLayout' is not a valid JSX element and cannot be used as such

Despite encountering similar questions, none of the provided answers seem to address the issue within my codebase. My project utilizes React 17, Mui v5, and TS v4. I attempted to integrate a basic component from an external package called rc-dock. I simply ...

Oops! Issue encountered while trying to read the file "src/core/database/config.ts"

Need help with migrating a database in a Node Nest.JS application. When running the npx sequelize-cli db:migrate shell command, I encountered the following exception: Error details: Error: TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".t ...

Combining Angular and Bootstrap: how to create two overlapping divs

Looking to enhance a project in Angular 15 + bootstrap 5 by creating two draggable divs where the lower one can be vertically resized to overlap the upper one? I've managed to set up most of it, but when dragging the lower div, its transparency makes ...

"What is the best way to transform a POST curl request into an Angular HTTP POST request using gsutil for Google Cloud Storage

Currently utilizing GCP and GCS. I am attempting to send a POST request, however in the curl command below, I am unable to locate where to input the necessary data that needs to be sent. In this scenario, how can I implement a POST request using angular ...

What methods can be used to test scss subclasses within an Angular environment?

Exploring different background colors in various environments is a task I want to undertake. The environments include bmw, audi, and vw, with each environment having its own unique background color. Need help writing an Angular test for this? How can I mod ...

Issue: The JSX element 'X' is missing any constructors or call signatures

While working on rendering data using a context provider, I encountered an error message stating "JSX Element type Context does not have any constructor or call signatures." This is the code in my App.tsx file import { Context } from './interfaces/c ...

Retrieving data and parameter data simultaneously from the ActivatedRoute

I am currently utilizing Angular and have a webpage where I need to send data to another page. Transmit an array of selected values Generate multiple records (associating with a model) this.activatedRoute.data.subscribe(({ model] }) => { setTim ...

Checking for String Const Type in TypeScript

In my code, I have a custom type called Admin with two possible values: 'ADMIN' or 'AGENT'. There is a function that retrieves the user role from local storage: return localStorage.getItem('role'); I am looking to verify if ...