Angular5 - Modify a public variable using an intercept in a static service

Take into account the following Angular service:

@Injectable()
export class AuthService {
     public userConnected: UserManageInfo;
     getManageInfo(): Observable<UserManageInfo> {

       return this.httpClient
        .get('api/Account/ManageInfo', { headers: this.getCustomHeaders() })
        .catch((error: Response) => {
            if (error.status == 401)
                return this.logout();
            return Observable.throw(error)
        })
        .map((response: any) => {
            this.userConnected = response;
            return this.userConnected;
        });
     }
}

The method getManageInfo() is called from the file app.component.ts. Moreover, upon application startup, the constructor of another component named AppSidebarComponent should retrieve this information.

Currently, I am handling it in the following manner:

export class AppSidebarComponent implements OnInit {
    public currentUser: UserManageInfo = new UserManageInfo();

    constructor(private authService: AuthService) {
          this.currentUser = this.authService.userConnected;
    }
}

However, when the property changes, the currentUser attribute within the AppSidebarComponent does not reflect the update.

What would be an effective way to address this issue?

Answer №1

If you encounter situations like this, it is a standard practice to utilize the BehaviorSubject from rxjs:

@Injectable()
export class AuthenticationCheck {
     public ActiveUser = new BehaviorSubject<UserInfo>(null); // instantiate and set to null initially

     verifyInfo(): Observable<UserInfo> {
       return this.httpClient
        .get('api/Account/UserInfo', { headers: this.getCustomHeaders() })
        .catch((error: Response) => {
            if (error.status == 401)
                return this.signOut();
            return Observable.throw(error)
        })
        .do(response => this.ActiveUser.next(response)); // remember to subscribe somewhere for execution
     }
}

And in your component:

export class UserPanelComponent implements OnInit {
    public LoggedInUser: UserInfo = new UserInfo();

    constructor(private authenticationCheck: AuthenticationCheck) {
        this.authenticationCheck.ActiveUser.subscribe((data: UserInfo) => {
            this.LoggedInUser = data;
        });
    }
}

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

Testing Your Angular 7 Code: Unit Testing Made Easy

I am currently working on developing unit tests for this angular script: export class DataService { private csrfToken: string = ''; private isContentShown: BehaviorSubject<boolean> = new BehaviorSubject(true); constructor(private h ...

Error TS2393 in Typescript: Multiple function declarations found within a Node/Express application

In my TypeScript node + express application, I have implemented a function in some API routes that looks like this: function cleanReqBody(req) { req.body.createdBy = req.user; req.body.modifiedBy = req.user; req.body.modified = new Date(); } Howeve ...

"Mastering the art of debouncing in Angular using

I am facing an issue where, during a slow internet connection, users can press the save button multiple times resulting in saving multiple sets of data. This problem doesn't occur when working locally, but it does happen on our staging environment. E ...

Angular 10: Display a notification when all checkboxes have been ticked

I am currently working on a project that involves Angular 10. The initial requirement was as follows: Users are presented with a list from which they need to choose one option using radio buttons. For example: the user selects covid19 from the given lis ...

Stop accidental form submissions on iOS devices by disabling the return button

In my Ionic 3 application running on iOS, I encountered a bug that allows users to submit a form even when the submit button is disabled. Despite trying different solutions from this source, I have not been successful in resolving it. To prevent accidenta ...

Identifying the End of an HTML Video in Angular 2

Seeking assistance with detecting the end of an HTML video in Ionic2 (Angular2 and Typescript). The relevant code snippets can be found below: Template: <video poster="" id="v" playsinline autoplay webkit-playsinline onended="vidEnded()"> <s ...

What is the process of declaring a react-icons icon in TypeScript?

Having a dilemma with declaring the icon in my array that contains name and icon. export const SidebarMenuList: SidebarMenu[] = [ { name: "Discover", icon: <AiOutlineHome />, id: SidebarCategory.Discover, }, ] The SidebarMe ...

Tips for creating a recursive string literal type in Typescript

I need to create a type that represents a series of numbers separated by ':' within a string. For example: '39:4893:30423', '232', '32:39' This is what I attempted: type N = `${number}` | '' type NL = `${ ...

Error: Could not locate application for Ionic Serve command

I have been developing a project in Ionic2 on another computer. However, when I try to run ionic serve on my PC, an error message appears: 192.168.1.100:8100 Application not found I have configured my app to use a static IP address... How can I resolve ...

The Angular2 cli throws an error stating: "Cannot add a new entry to an existing one."

I have been utilizing the Angular2 Cli as my runtime environment for my Angular 2 application and I must say, I am thoroughly impressed by its architecture, top-notch development tools, and overall well-thought-out design. However, every so often, specifi ...

Step-by-step instructions for deactivating a specific FormControl within a FormArray

I've created a form that includes custom details: this.myform= new FormGroup({ ... customDetails: new FormArray([]), }); get customDetailsFormArray() { return this.shippingLocationDetailsUpdateForm.get( 'customDetails' ) as Form ...

Dealing with a multi-part Response body in Angular

When working with Angular, I encountered an issue where the application was not handling multipart response bodies correctly. It seems that the HttpClient in Angular is unable to parse multipart response bodies accurately, as discussed in this GitHub issue ...

Loading an Angular2 app is made possible by ensuring that it is only initiated when a DOM element is detected

In my main.ts file, the code below is functioning perfectly: import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app.module'; platformBrowserDynamic().bootstrapModule(AppModule); H ...

What is preventing me from downgrading Rxjs?

Looking for a solution to downgrade my rxjs package from version 6.1.0 to 5.5.4. Here's what I've tried so far: npm -v rxjs 6.1.0 npm install <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="73010b190033465d465d47"> ...

Start Transloco in Angular before the application begins

For our Angular project, we have implemented Transloco to handle translations. Within my typescript code, I am using the transloco service in this manner: this.translocoService.translate('foo.bar') I understand that it is crucial to ensure that ...

Validators in Angular forms are a powerful tool for enforcing

Is it possible to use Validators in the ts.file to display an error message when a field is invalid, rather than directly in the html? Thanks. html <form [formGroup]="form"> <mat-form-field> <mat-label>Nom</mat-label> ...

The file could not be located on the server during the project build and upload process

Presently, I'm engrossed in a project involving Angular 9 and ASP Core 3. You can find the website at: Nevertheless, encountering an error when trying to access this URL: http://mag-testcpl.astromap.ir/assets/vendors/global/toastr.css The culprit ...

Perform a series of observables from a dynamically generated array

Currently, I am in the midst of a project (Angular2) where I am dynamically creating Observables and storing them in an array. var ObservableArray : Observable<any>[] = []; //populating the Observable array dynamically for (var i = 0; i < this.ma ...

Utilize ngx-filter-pipe to Streamline Filtering of Multiple Values

Need assistance with filtering an array using ngx-filter-pipe. I have managed to filter based on a single value condition, but I am unsure how to filter based on multiple values in an array. Any guidance would be appreciated. Angular <input type="text ...

How can I adjust the indentation in Angular Prime-ng's p-tree component?

In my project, I am utilizing the primg-ng tree component for the sidebar. Currently, the output is displayed as shown here: https://i.stack.imgur.com/kcSQt.png However, I am looking to maintain consistent indentation levels without any adaptive changes ...