How to detect changes in Angular 2 using a separate service

Within my AuthService, I store real-time user data and a method for logging in. When the 'Login' button is clicked, the AuthService is called to retrieve updated user data from the server and update the value of 'this.user'.

As a result, the username is displayed in the header.

Now, the question arises: how can my HeaderComponent be notified when the 'this.user' value in the AuthService has been modified?

Answer №1

If you want to incorporate an Observable in your AuthService, you can do so by exposing it as a stream that can be subscribed to in your HeaderComponent. A useful approach is to utilize the EventEmitter class, which is an extension of the RxJS Subject class. Additionally, employing a TypeScript setter can automatically trigger events for any changes made. Your implementation may resemble the following:

@Injectable()
export class AuthService {
    private _user: any;
    userStream: EventEmitter<any>;

    constructor() {
      this.userStream = new EventEmitter();
    }

    //code ...

    getUserData() {
        //invoke our setter function
        this.user = newData;
    }

    set user(newValue) {
        this._user = newValue;
        //update user data and emit a value through the userStream
        this.userStream.emit(newValue);
    }
}

You can then integrate your service into your component like so:

@Component({...})
export class HeaderComponent {
    currentUser: any;

    constructor(private authService: AuthService) {
        //subscribe to the stream to receive notifications when user data changes
        authService.userStream.subscribe((newUser) => { this.currentUser = newUser; });
    }
}

This setup allows you to monitor changes within your user data effectively.

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

Retrieve the value of the Observable when it is true, or else display a message

In one of my templates, I have the following code snippet: <app-name val="{{ (observable$ | async)?.field > 0 || "No field" }}" The goal here is to retrieve the value of the property "field" from the Observable only if it is grea ...

Exploring object manipulation and generating unique identifiers by combining values - a beginner's guide

After analyzing the provided data, my goal is to come up with a method of combining the IDs and returning an array of their corresponding keys. // example data var data = [ { id: 1, key: 'a' }, { id: 1, key: 'b' }, { id: 2, key ...

Adding individual buttons at the bottom of each data row using Jquery: A step-by-step guide

Currently, I am receiving data from a backend using an AJAX GET method and displaying it in a list in HTML. However, I am facing some issues with including buttons within the list and making them functional by utilizing delegate and other methods. I would ...

Transform nested entities into a single entity where any properties that are objects inherit from their parent as prototypes

Exploring a new concept. Consider an object like: T = { a: 2, b: 9, c: { a: 3, d: 6, e: { f: 12 } } } The goal is to modify it so that every value that is an object becomes the same object, with the parent object as prototy ...

Experiencing difficulties integrating relational data with Angular and MongoDB

I have a view where I display 'Transporters'. Each Transporter has multiple 'Deliveries', so I want to associate Deliveries with the corresponding Transporters. My tech stack includes express, mongoose, and angular.js. Here are my mode ...

Unexpected JSON token error occurs in jQuery when valid input is provided

I encountered an error that I'm struggling to pinpoint. The issue seems to be related to the presence of the ' symbol in the JSON data. After thoroughly checking, I am positive that the PHP function json_encode is not responsible for adding this ...

struggling with utilizing ajax for outputting data using PHP and POST variables

Currently, I am attempting to execute a PHP script that retrieves data from a database by simply clicking a button. My intention is to implement AJAX in order to prevent the page from refreshing. While testing with traditional post/submit methods and enc ...

Switching the endpoint renders the middleware ineffective

I've encountered a puzzling issue with my NodeJs - Express server, which serves as the backend for my mobile application. The problem arises when I send post requests to certain endpoints like checkmail and checkusername using axios from the frontend ...

Showing a notification on the screen upon redirection to the index page

On my main index page, there are 18 divs representing different books. When a user clicks on a div, they can see details about the book such as title, author, and summary. There's also an option to add the book to a Collections array by clicking the " ...

How can I apply a class to an Angular tag that already has existing CSS classes in the HTML template?

I am looking to write code similar to the following: Note: I do not have control over the classes in the class property (style13, style121, style541), but I want to add another class from a variable in the TypeScript. For example: <div class="styl ...

Implementing ES6 Angular directives with two-way isolated binding

I'm really struggling to understand how isolating scopes function in my code. Interestingly, everything seems to work fine when I remove the scope part of the directive. Can someone please shed some light on what I might be overlooking? export func ...

Using Angular 8 to Pass Form Data to Another Component via a Service

Is there a way to send all the Formgroup data as a Service in Angular to Another Component without using ControlValueAccessor? I want the receiver to automatically receive the value data whenever someone enters information on a form. I am attempting to mo ...

Numerical values are not considered by the JavaScript table filter

I'm having trouble with dynamically filtering the content. It works fine for the first two columns, but not for the third one. Maybe I need some additional JavaScript? Here is the link to my snippet: `https://www.w3schools.com/code/tryit.asp?filen ...

How do I access the current state in Ngrx Store without the need to subscribe, specifically for use in a route Resolve?

Presently, my Resolve implementation is quite straightforward: export class UserResolve implements Resolve<any>{ constructor(private userService: UserService){} resolve(route: ActivatedRouteSnapshot){ return this.userService.get(route. ...

Organize information in a React table following a predetermined sequence, not based on alphabetical order

As a beginner with React, I'm looking to sort my data by the column "Status" in a specific order (B, A, C) and vice versa, not alphabetically. The data structure looks like this: export interface Delivery { id: number; name: string; amount: num ...

Switching from HTML to BBCode during the editing process

My issue lies in converting BBCode to HTML and then editing the code on a page with AJAX. When editing in a <textarea>, the HTML tags show up instead of the original BBCode. For instance, if I submit [b]bold text[/b] and save it to my database, the ...

What steps should I take to make the code in jsfiddle functional on my Visual Studio Code platform?

const canvasEle = document.getElementById('drawing-container'); const canvasPad = document.getElementById('pad'); const toolbar = document.getElementById('toolbar'); const context = canvasEle.getContext('2d'); const ...

"Encountering a challenge when trying to populate a partial view using AngularJs and MVC

I am a beginner in AngularJS and I'm using a partial view for Create and Edit operations, but I'm encountering issues while trying to retrieve the data. The data is successfully being retrieved from my MVC controller but it's not populating ...

Removing sourceMappingURL from an Angular Universal build: A step-by-step guide

Using this repository as my foundation, I have successfully resolved most of the plugin errors except for one that continues to elude me. It's puzzling because no other plugin anticipates a .map file in an SSR build since it is intended for productio ...

Determining the inner type of a generic type in Typescript

Is there a way to retrieve the inner type of a generic type in Typescript, specifically T of myType<T>? Take this example: export class MyClass { myMethod(): Observable<{ prop1: string, ... }> { .... } } type myClassReturn = ReturnTy ...