How can Angular 2 effectively keep track of changes in HTTP service subscriptions? Calling the method directly may result in

After making a call to the authentication service method that checks the validity of the username and password, as well as providing an authentication token, I encountered an issue. When attempting to display the value obtained from calling the getAuthData method, it consistently showed the default/invalid value for authData.status - false.

Curiously, when I rendered the value in my template view using {{authData.status}}, it displayed the correct value after form submission. Despite extensive research through Google and documentation, I have not been able to resolve this mystery. Do I need to subscribe to service changes or is there something crucial that I am overlooking?

The problem seems to stem from the authSubmit() method in admin.component.ts

admin.module.ts

import { NgModule }       from '@angular/core';
import { CommonModule }   from '@angular/common';
import { FormsModule }    from '@angular/forms';
import { AdminComponent } from './admin.component';
import { AuthService }    from '../shared/auth/index';

@NgModule({
    imports: [CommonModule, FormsModule],
    declarations: [AdminComponent],
    exports: [AdminComponent],
    providers: [AuthService]
})

export class AdminModule { }

auth.service.ts

import { Injectable }     from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable }     from 'rxjs/Observable';

import 'rxjs/add/observable/throw';

export class AuthData {
    public status: boolean;
    public token:  string;

    public constructor(initStatus: boolean = false, initToken: string = '') {
        this.status = initStatus;
        this.token  = initToken;
    }
}

@Injectable()
export class AuthService {
    public authData: AuthData;

    public constructor(public http: Http) {
      this.authData = new AuthData();
    }

    public getAuthData(user: string, pass: string): Observable<AuthData> {
        return this.http.get('http://api.dev/auth?user=' + user+ '&pass=' + pass)
            .map((res:Response) => res.json())
            .catch((error:any) => Observable.throw(error.json().error || 'Error'));
    }
}

admin.component.ts

import { Component }             from '@angular/core';
import { AuthService, AuthData } from '../shared/index';

@Component({
    moduleId: module.id,
    selector: 'my-admin',
    templateUrl: 'admin.component.html',
    styleUrls: ['admin.component.css']
})

export class AdminComponent {
    public authUser: string;
    public authPass: string;

    public authData: AuthData;

    public constructor(public authService: AuthService) {
        this.authData = this.authService.authData;
    }

    public authSubmit(): boolean {
        this.authService.getAuthData(this.authUser, this.authPass)
        .subscribe(
            data => this.authData = data,
            err  => console.log(err)
        );

        // alert result: authData.status = false | should be: true
        alert('authData.status= ' + authdata.status);

        return false;
    }
}

admin.component.html

  <form *ngIf="!authData.status" (submit)="authSubmit()">
      <input [(ngModel)]="authUser" type="text">
      <input [(ngModel)]="authPass" type="password">

      <button type="submit">Sign In</button>
  </form>

  authData.status = {{authData.status}}

Answer №1

Finally figured it out, after making a silly mistake and finding an easy fix.

function checkAuthentication(): boolean {
    let isAuthenticated: boolean = false;

    authService.fetchUserData(username, password)
    .subscribe(
        response => {
          authService.userData = response;
          isAuthenticated = response.valid;
        },
        error  => console.log(error)
    );

    alert('User is authenticated: ' + isAuthenticated);

    return false;
}

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

Using a split string to destructure an array with a mix of let and const variables

There is a problem with TS: An error occurs stating that 'parsedHours' and 'parsedMinutes' should be declared as constants by using 'const' instead of 'prefer-const'. This issue arises when attempting to destructure ...

Incorporate the Angular async pipe along with BehaviourSubject/ReplaySubject to enhance performance with auditTime/debounceTime

Trying to subscribe to a BehaviorSubject/ReplaySubject using the Angular async pipe has been challenging for me. In addition, I need to incorporate either the auditTime or debounceTime operator to filter out certain values. Below is an example (I utilized ...

Can the Node DNS module be incorporated into Angular code?

I am facing a requirement where I must perform a DNS lookup from client-side code built in Angular. Is it feasible to utilize the DNS module from https://nodejs.org/api/dns.html in Angular? ...

Encountering issues when attempting to set up graphqlExpress due to type

This is my first experience using GraphQL with Express. I have created a schema: import { makeExecutableSchema } from "graphql-tools"; import { interfaces } from "inversify"; const schema = ` type Feature { id: Int! name: String ...

Tips for running a post-installation script when deploying an Angular 4 application to an Azure website using KuduScript

I recently faced an issue with my angular4 app deployed on azure web app (website) using Deployment Options through the Portal. To customize the deployment script, I utilized kuduscript [kuduscript -y –node] and modified deploy.cmd to specify how Azure s ...

Adding an image file to a folder

Just a quick query I have regarding the process of uploading an image to a collection in mongoDB. My current collection of candidates looks like this: {name: "", role: "", support: ""}. I'm curious if it's possible to include an image within the ...

What is the best way to incorporate a custom string into an Angular application URL without disrupting its regular operation?

In my Angular application with angular ui-router, I am facing an issue with the URL structure. When I access the application from the server, the URL looks like localhost/..../index.html. Once I click on a state, the URL changes to localhost/.../index.htm ...

Error: The specified module 'tty' was not found in the directory '/workspace/node_modules/pace/node_modules/charm'

My attempt to compile my frontend project using ng build resulted in the following error message: ERROR in ./node_modules/pace/node_modules/charm/index.js Module not found: Error: Can't resolve 'tty' in '/workspace/node_modules/p ...

The width of mat-table columns remains static even with the presence of an Input field

I'm currently working on an Angular component that serves the dual purpose of displaying data and receiving data. To achieve this, I created a mat-table with input form fields and used {{element.value}} for regular data display. Each column in the tab ...

Error: An unexpected token < was caught in the TypeScript Express code

Using TypeScript to compile and run an Express server that simply serves an HTML file. However, encountering an error in the response under the network tab in Chrome for app.js: Uncaught SyntaxError: Unexpected token '<' Below is the server c ...

Troubleshooting a navigation issue in Angular involving the mat-sidenav element of material UI while transitioning between components

I would greatly appreciate your assistance in resolving the issue I am facing. I have been trying to navigate from one view to another, but when I use an <a> tag nested within a <mat-sidenav>, I encounter the following error: "Uncaught (in prom ...

Unable to bind to ngModel as it returned as "undefined" in Angular 8

Whenever I bind a property to ngModel, it consistently returns undefined <div> <input type="radio" name="input-alumni" id="input-alumni-2" value="true" [(ngModel) ...

How can I prevent buttons from being created using ngFor in Angular?

I need help with creating an HTML table that includes a cell with a button and a dropdown generated using ngFor. How can I disable the buttons (generated via ngFor) if no value is selected from the dropdown? Here's what I have tried so far: In my App ...

Retrieve a specific nested key using its name

I am working with the following structure: const config = { modules: [ { debug: true }, { test: false } ] } My goal is to create a function that can provide the status of a specific module. For example: getStatus("debug") While I can access the array ...

An error has occurred in Node.js/Express.js: The path argument is missing and is required for res.sendFile

I have successfully uploaded my files using Multer to a specific directory. However, I am now facing an issue while trying to download the same files that are displayed in an HTML table with individual download options. Below is the code snippet: Node.j ...

Getting the Value of a CSS Class through Form Name in Angular

I am attempting to retrieve the class name of a form control using the Form Name both in HTML and in the Class file The code snippet below functions correctly and shows the value of the control {{ModelForm.value.firstName| json}} However, when I try to d ...

Troubleshooting the error message "XMLHttpRequest cannot load" when using AngularJS and WebApi

I have developed an asp.net webApi and successfully published it on somee.com. When I access the link xxxx.somee.com/api/xxxx, everything works fine. However, when I try to call it in Angularjs, it does not work. $http.get('http://xxxxxx.somee.com/ap ...

Differences in Behavior when using $http and Restangular for POST Requests

Currently, I am using a basic ASP.NET Web API 2 service. As someone new to Angular, I decided to transition from utilizing $http to Restangular. Although my GET request seems to be functioning properly, there are issues with my POST request. This is how t ...

Is it possible to include parameters in an HTML GET request with Electron.Net?

I have successfully implemented a function in an Angular component within an Electron application using HttpClient: var auth = "Bearer" + "abdedede"; let header = new HttpHeaders({ "Content-Type": 'application/json&a ...

What is the best way to create Jest unit tests for an Angular Component without using TestBed?

I'm diving into the world of Jest testing and feeling lost as to why my tests keep failing. If you have any recommendations for videos or articles that focus on writing Jest unit tests for Angular components and services without using "TestBed," plea ...