Accessing instance variables from a chained observable function in Angular 2/Typescript

Currently, I am utilizing Angular2 along with Typescript. Let's assume that there is a dummy login component and an authentication service responsible for token authentication. In one of the map functions, I intend to set the variable authenticated as soon as the token is received from the backend server.

The dilemma I am facing is that I am unable to access the instance variable within the chaining function. The this inside the chaining function actually refers to the subscriber of this observable. Although I understand that this issue stems from scope problems, finding a solution has proven to be challenging.

export class AuthenticationService {
authenticated:boolean = false; //the desired variable to be accessed

constructor(public http: Http) {
    this.authenticated = !!sessionStorage.getItem('auth_token');
}

login(username, password) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    return this.http
      .post(
        'http://localhost:8080/token-auth',
        JSON.stringify({ username, password }),
        { headers }
      )
      .map(res => res.json())
      .map((res) => { 
        if (res) {
            this.authenticated = true;  //where I aim to access the instance variable
            sessionStorage.setItem('auth_token', res.token);
        }

        return res;
      });
}

The dummy-login component where the aforementioned login() method is invoked appears as follows:

export class DummyLoginComponent {
  constructor(private auth: AuthenticationService, private router: Router) {
  }

  onSubmit(username, password) {

    this.auth.login(username, password).subscribe((result) => {
        if (result) {
            this.router.navigate(['Dashboard']);
        }
    })
  }
}

Answer №1

Instead of using mapping, you have the option to simply subscribe to the observable directly

authenticate(username, password) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    let response = this.http
      .post(
        'http://example.com/authenticate',
        JSON.stringify({ username, password }),
        { headers }
      )
      .map(response => response.json());
    response.subscribe(
      (result) => { 
            this.authenticated = true;  //this is where I intend to modify the instance variable
            sessionStorage.setItem('auth_token', result.token);
    });
    return response;
}

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

Embracing Angular2 - incorporating external modules

Attempting to incorporate the phoenix_js NPM module into my Angular2 app (which was created using the Angular2 CLI) is proving to be a challenge. I keep encountering the error message Cannot find module 'phoenix_js'. Many others have also faced t ...

Angular Unit Test: Received 1 argument instead of the expected 3

Currently, I am in the process of unit testing an Angular application. This is my first time venturing into Angular Unit Testing. To save time, I downloaded the angular app from here. As a beginner in Unit Testing, I watched some informative videos on the ...

Verify whether the value is considered false, true, or null

When dealing with variables in JavaScript, I often need to determine if a variable is false, true, or null. If the variable is null or undefined, I want to assign an array to it by default. While this syntax works well in other languages, in JS assigning a ...

When converting an NgbDate to a moment for formatting needs, there is a problem with the first month being assigned as 0 instead of 1

I am encountering a challenge with my Ngb-Datepicker that allows for a range selection. To customize the output format, I am using moment.js to convert the NgbDate into a moment object (e.g., Wed Jan 23). One issue I encountered was that NgbDates assign J ...

The functionality of Angular 8 Directives from the shared module is currently malfunctioning

Hey everyone! I've been working on creating a custom directive in Angular 8, but for some reason it's not functioning properly. Even though there are no errors shown in the browser console, I can't see any changes or output from the console. ...

The process of subscribing to a service in Angular

I currently have 3 objects: - The initial component - A connection service - The secondary component When the initial component is folded/expanded, it should trigger the expansion/folding of the secondary component through the service. Within the service ...

What is the best way to restrict a mapped type in typescript to only allow string keys?

In the Typescript documentation, I learned about creating a mapped type to restrict keys to those of a specific type: type OptionsFlags<Type> = { [K in keyof Type]: boolean; }; If I want to use a generic type that only accepts strings as values: t ...

Utilizing a dynamic value in an Angular directive

For my latest project, I am working on developing a basic JSON pretty-printer directive using angular.js. Here is the code snippet I have so far: (function(_name) { function prettyJson() { return { restrict: 'E', ...

At times, the animation in SetInterval may experience interruptions

I have created an animation using a sequence of images. The animation runs smoothly with the setinterval function, but for some reason, it occasionally pauses. I've shared a fiddle where you can see this pause happening. Click Here to See the Unwante ...

Head to the "/unauthorised" route in Angular while maintaining the current URL intact

I have a security guard that directs the user to an "/unauthorised" route when they do not have permission to access the current page (which could be any page). @Injectable() export class PermissionGuard implements CanActivate { constructor(private reado ...

Shifting the use of @Inject(MAT_DIALOG_DATA) away from class constructors

Our team is making a transition in the Dependency Injection pattern we utilize to minimize the dependency on TypeScript constructors. This shift will help us address recurring issues caused by team members adding logic that shouldn't be included in co ...

Generate time-dependent animations using circles

Hey there, I am trying to create an animation that involves drawing three circles and having one of them move from right to left. The circles should appear randomly in yellow, blue, or orange colors on the canvas at different intervals (3 seconds between ...

Ways to broaden the type signature of a Typescript comparator in order to facilitate sorting by properties nested within objects?

Here is a function that I created: arr.sort(alphabeticallyBy("name")) The function has the following signature: <T extends string>(prop: T) => (a: Partial<Record<T, string>>, b: Partial<Record<T, string>>) => ...

When using MathJax on an iPhone with a device width setting, you will experience the

Utilizing MathJax to display mathematical symbols on a mobile device- such as an iPhone, I encountered an issue with the meta tag: <meta name="viewport" content="user-scalable=no, width=device-width" /> This seemed to be causing problems as the Mat ...

Could not locate module: Issue: Unable to resolve './Firebase'

I'm a beginner with React and I've been working on setting up Firebase in my React application. import firebase from 'firebase/compat/app'; import 'firebase/compat/auth'; import 'firebase/compat/firestore'; var fire ...

Why is the radio button not chosen in the ns-popover popup? The radio button is only selected in the popup of the last column

In my Angular controller, I am trying to set the radio model but it is only appearing in the last column popup of the table. The ns-popover is displayed when clicking on a table column. Here is the Angular Code: var app = angular.module('app', ...

Trouble with Bootstrap 3's nav-justified feature not displaying correctly upon window expansion

Looking at this Bootstrap example page, I noticed a small issue with the nav-justified navigation. When the window is minimized, it transitions correctly to a mobile version. However, when the window is maximized again, the buttons remain in the mobile for ...

Leverage Firebase cloud functions to transmit a POST request to a server that is not affiliated with

Is it feasible to utilize a firebase cloud function for sending a post request to a non-Google server? It appears that being on the blaze plan is necessary in order to communicate with non-google servers. Essentially, I aim to perform a POST action to an ...

Keep the sub-menu in a kendo context menu from closing until the user either hovers over another menu item or clicks outside of the current item

Please take a look at this example: Due to the small size of sub-items, the sub-menu closes quickly when hovering over the menu and losing focus. My goal is to keep an opened sub-menu from closing until the user hovers over another menu item or clicks on ...

Present a pop-up notification box with a countdown of 30 seconds prior to the expiration of a session timeout in JSF

Our task is to create a timeout window that appears 30 seconds before the session expires. If the user remains inactive, they will be automatically redirected to the home page. We already have the maximum allowed duration of inactivity defined. I would l ...