Tips for sharing data between components that have been previously loaded in Angular 7

Hey everyone, I am currently working on an Angular project where upon login, the back end API generates a JWT token that is then passed to the front end. After getting the JWT token, I decode it to extract some details in the login.component.ts file. Now, I want to pass this decoded data to my top-bar component. The challenge here is that the top-bar component has already been loaded in the application. Can anyone guide me on how to achieve this?

Using Angular 7 CLI

Login.component.ts


onSubmit(form:NgForm){

  //some code here for login authentication----------------

  const helper = new JwtHelperService();
  const decoded= helper.decodeToken(result.token);
  console.log(decoded);

}

Top-Bar.component.ts

ngOnInit() { }

Answer №1

You can achieve this by following these steps:

First, create a shared service with the name loginSubject:

@Injectable()
export class StateService {
    loginSubject: Subject<any> = new Subject();

    ...
}

Next, emit a message in the Login.component.ts:

constructor(
  private stateService: StateService
) {}

onSubmit(form: NgForm) {

  // Code for login authentication goes here

  const helper = new JwtHelperService();
  const decoded= helper.decodeToken(result.token);
  this.stateService.loginSubject.next(decoded);
  console.log(decoded);

}

Finally, subscribe to the loginSubject in Top-Bar.component.ts:

constructor(
  private stateService: StateService
) {}

ngOnInit() {
  this.stateService.loginSubject.subscribe(data => {
    // Do something with the decoded data
  });

  ...
}

Answer №2

When it comes to interacting with Angular Components, there are several approaches you can take:

1) If you need to display Top-Bar.component.html within the login html, you can pass in the value to Top-Bar.component.ts using an @Input variable. For more information, refer to the official Angular documentation on component interaction: https://angular.io/guide/component-interaction

2) If Top-Bar.component is completely independent of the login module, you can create a service and assign the variable to the service for component interaction. Refer to the following tutorial for more details: https://angular.io/tutorial/toh-pt4

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

What is the best way to implement a hover effect on multiple rows within an HTML table using Angular?

I am currently working on developing a table preview feature to display events. I previously sought assistance here regarding positioning elements within the table and successfully resolved that issue. Applying the same principles, I am now attempting to c ...

Exploring the best way to access ViewContainerRef: ViewChild vs Directive

While researching, I came across a recommendation in the Angular Docs that suggests using a directive to access the ViewContainerRef for creating dynamic components. Here is an example of such a directive: import { Directive, ViewContainerRef } from &apos ...

Exploring the Pristine State of Nested Controls in Angular Reactive Forms

I'm currently in the process of putting together a nested form that's relatively simple. Form Group > Form Array > Form Group > Controls Within the HTML, I am attempting to include a Remove button that will only display when the last i ...

How to ensure Service is loaded before App Component in Angular 6?

My Data service is responsible for fetching the JSON Object value, however all components load before the data service finishes loading. This results in undefined values when I call the service method from components. ...

What's the reason behind receiving these warnings?

After installing dependencies or libraries using npm, I often encounter errors or warnings in the command prompt similar to the following: npm WARN <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6b0a050c1e070a19460f0a1f0a1f0a0 ...

Establish a set height for ngx-datatable component in Angular version 4

Looking for guidance on setting up a table in an Angular 4 application using the swimlane/ngx-datatable. The table requires the property scrollbarV, and I want to achieve a fixed height with a scroll bar, similar to the example provided by them. However, i ...

Adding a new data source to Mapbox

When working with mapbox, I encountered a 404 error while trying to load a layer from a variable geojson. The addSource data function always expects the data to be a URL. Is there a way to use variables instead? this.map.on('load', () => { c ...

Issue TS2322: Type 'Observable<string[]>' is not compatible with type 'Observable<Sensors[]>'

This issue: error TS2322: The type 'Observable' cannot be assigned to the type 'Observable'. The type 'string[]' cannot be assigned to the type 'Sensors[]'. The type 'string' cannot be assigned to th ...

Discover the perfect way to implement true lazyloading using NativeScript Angular tabs and BottomNavigation

Currently working on an app using nativescipt, I've successfully added BottomNavigation with lazy loading and Tab components in child pages. The code structure resembles the following: export const routes: Routes = [ { path: '', red ...

Creating a type definition for an object literal constant with intricate property types

I am looking to create a constant object literal in TypeScript with a long list of properties all having the same type. Here is an example definition with only three properties: type ContainerSize = { height: string; width: string; threshold?: number ...

Authentication and account system with .NET Core Backend and Angular2 Frontend for seamless user login and security measures

I've hit a roadblock in the initial stages of my new project, specifically with setting up account management. My project involves using Angular2 on the frontend, connected to a .NET Core WEB API & Backend that interfaces with a MySQL database via En ...

identifiers that have been duplicated errors

My journey with VS 2017 and angular 2 started off smoothly, but I hit a roadblock when I encountered 352 errors upon restarting my machine. The errors were mostly "Duplicate Identifier errors," and after some investigation, I realized that I had the file i ...

Angular TimeTracker for tracking time spent on tasks

I need help creating a timer that starts counting from 0. Unfortunately, when I click the button to start the timer, it doesn't count properly. Can anyone assist me in figuring out why? How can I format this timer to display hours:minutes:seconds li ...

Troubleshooting Error in Angular2 ngFor: "Encountered issue with reading property '0' of undefined"

I am attempting to retrieve data from a JSON file in order to create a form. Below is a snippet of my template: <div class="form-group"> <label for="power">Power</label> <select class="form-control" id="power" required> ...

What is the best way to fill the dropdown options in every row of a data table?

This HTML snippet displays a data table with test data and corresponding dropdown options. <tr> <th> Test Data </th> <th> Test Data ...

Is having only one FCM token sufficient for storing data from multiple devices?

I'm currently working on an Angular website and looking to send push notifications to users subscribed on both desktop and mobile. I am utilizing Firebase Cloud Messaging for this purpose and wondering if storing a single FCM token will suffice for se ...

Eliminate a descendant of a juvenile by using the identification of that specific juvenile

Here is the current structure I'm working with: https://i.sstatic.net/TejbU.png I want to figure out how to eliminate any field that has the id 3Q41X2tKUMUmiDjXL1BJon70l8n2 from all subjects. Is there a way to achieve this efficiently? admin.databa ...

Is it feasible to utilize GraphQL subscriptions with Azure Functions?

Exploring the potential of implementing GraphQL subscriptions on Azure Functions. Unfortunately, it seems that apollo-server-azure-functions may not be compatible. Are there any other options or strategies to successfully enable this functionality? ...

Oops! Looks like there was an error trying to assign the value "$event" to the template variable "element". Remember, template variables can only be read

Can anyone assist me in identifying the issue with this code? <div *ngFor="let element of list; let index=index"> <mat-form-field> <input matInput type="string" [(ngModel)]="element" name="element ...

Using JavaScript to assign function arguments based on arbitrary object values

I am facing a challenge with a collection of arbitrary functions and a method that takes a function name along with an object or array of parameters to call the respective function. The issue arises from the varying number of inputs in these functions, som ...