Using Angular2 to Inject a Service into Another Service

I'm having trouble locating my mistake.

app.module.ts
    ...
    providers: [ValidateService,AuthService]
    ...

In the register.component.ts file, I perform the following actions:

import {AuthService} from '../../services/auth.service';
...
constructor( private _validateService: ValidateService,
               private _fms: FlashMessagesService,
               private _authService: AuthService,
               private _router: Router
               ) { }
...
ngOnInit() { 
      this._authService.uniqueUser({username:'zomh'}).subscribe(data => {
      console.log("data.success: "+data.success);       
      if(!data.success) {   // Username already exists       
        console.log('exists');
      }
      else {
         console.log('does not exist');
      }
      });
  }

As expected, when registering a user who is already in the database, I see the message "user exists" in the console.

The same process is applied (simplified to this point) in the validate.service.ts file:

import { AuthService } from './auth.service';
import { Injectable } from '@angular/core';
import { FormControl } from '@angular/forms';

@Injectable()
export class ValidateService {

  constructor( public _authService: AuthService) { }

  validateRegister(user) {
    if(user.name == undefined || user.email == undefined || user.username == undefined || user.password == undefined)
      return false;
    else
      return true;
  }

  // Other validation methods...

  validateUsernameIsUnique (c: FormControl) {

    let ret:any;
    if (c.value.length >= 3)
    {
      console.log(c.value);
      this._authService.uniqueUser({username:'zomh'}).subscribe(data => {

      if(!data.success) {   
        console.log('call from service: exists');
      }
      else {
         console.log('call from service: does not exist');
      }
      });

    }

    return {usernameIsTaken:true};
  }


}

However, I encounter a

Cannot read property _authService of undefined
Exception. For me, it seems like the service was not injected correctly. But pinpointing the error has proven difficult.

Update 1: After copying the auth Service call into the Constructor and seeing success, it appears that there may be an issue with referencing this. in other methods outside of the constructor?

@Injectable()
export class ValidateService {

  constructor( private _authService: AuthService ) { 

        this._authService.uniqueUser({ username: 'zomh' }).subscribe(data => {

        if (!data.success) {   // Username already exists       
          console.log('call from service: exists');
        }
        else {
          console.log('call from service: does not exist');
        }
      });
  }

Answer №1

It appears that adding a new line between @Injectable and export class ValidateService { may cause some issues.

I suggest removing that extra line to see if it resolves the problem.

Answer №2

After skimming through an article, I decided to revamp my approach by transforming it into an instance method:

 checkIfUsernameIsUnique = (control: FormControl) => {

    let result: any;
    if (control.value.length >= 3) {      
      this._authenticationService.verifyUserUniqueness({ username: control.value }).subscribe(response => {

        if (!response.success) {   // The username already exists       
          console.log('Call from service: User exists');
        }
        else {
          console.log('Call from service: User does not exist');
        }
      });

    }
...

This adjustment effectively resolved the issue at hand. I am still uncertain as to why this modification was necessary, so please share any insights you may have.

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 setTimeout with drag and drop functionality in HTML

I need a setTimeout function to be triggered only after dragging and dropping an image into a division, not before the drop occurs. ...

Applying Validators manually in Angular 2 beta 17

We are currently working on a legacy project that needs to be maintained until the final version with angular-final is deployed. Once we upgrade to the final version, I will be able to easily apply conditional Validators using: this.myForm.controls[&apos ...

Unfortunately, despite attempting to kill all processes linked to port 4200, it seems that it is still in use

Getting angular up and running on my Mac OS X 10.11.3 El Capitan has been quite a challenge. After installing nodeJS and npm, I used npm to install angular-cli. To create a new app, I executed the command sudo ng new first-app Then, I navigated into the ...

Locate the index position of an element in one array based on a corresponding element in a

I am seeking a way to determine the index and group that an item belongs to within a parent json group. Is there a method for achieving this? I am willing to modify the json format if necessary. I made an attempt using JSON.stringify(), but it seems to be ...

Convert HTML to PDF and ensure that the table fits perfectly on an A4

I am currently utilizing html-pdf to convert my table data into a PDF format. The issue I am facing is that the table content exceeds the specified A4 paper size in such a way that two columns are completely missing in the generated PDF. However, when I c ...

Ways to make the sole element you've designed fade into view

I have a function that creates a note in the DOM. The issue is that when the note is created, it adds the "fade in" animation class to all notes instead of just the one being created. How can I modify it so that only the newly created note will have the ...

Incorporate Angular Material into a personalized library

In my quest to create a reusable library for various projects, I decided to embark on building my own from scratch. The process began with the formation of a new application solely dedicated to housing this library: ng new lib-collection cd lib-collection ...

Utilizing JavaScript to Incorporate Node Packages

Sorry for the basic question, as I am fairly new to web development and JavaScript. I am trying to utilize a package that I installed via npm called shopify-buy by following the instructions provided at: The package is located in my node_modules director ...

Module augmentations do not allow for exports or export assignments

import { Request as ExpressRequest, Response as ExpressResponse } from 'express'; declare module 'kvl' { export = kvl; } declare const kvl: { ValidationDone:(param:(error: any, response: ExpressResponse) => void) => void; ...

Difficulty with the Testimonials Carousel Javascript

I'm currently attempting to create a Testimonials slider using JavaScript, but I'm facing an issue with the slider not transitioning to the next slide. It functions correctly when on the first or last slide, but fails to move otherwise. I've ...

Animate the transition of the previous element moving downward while simultaneously introducing a new element at the top

I currently have a hidden element called "new element" that is controlled by v-if. My goal is to create a button labeled "display" that, upon clicking, will reveal the new element on top after sliding down an old element. How can I achieve this using CSS ...

Retrieve the value of a dropdown menu that contains multiple selections associated with a single model

My current code generates a calendar entry listing for the courtroom, with each case having a "status" dropdown that is set by the judge post-hearing. I now need to save this data in the database. I have successfully added ng-change which triggers the desi ...

Get back a variety of substitutions

I have a variety of different text strings that I need to swap out on the client side. For example, let's say I need to replace "Red Apple" with "Orange Orange" and "Sad Cat" with "Happy Dog". I've been working on enhancing this particular ques ...

A guide on using JavaScript to obtain the original calculation for a specific equation once a checkbox has been unchecked

I am facing a scenario where I have two input fields. One should display the value of Quantity, and the other should display the value of Price. The first input, which is for quantity and of type number, has the disabled attribute. However, upon checking a ...

A guide on implementing multiple ternary operators in a Vue.js template

Is it possible for a template to return three different values instead of just two, based on the data? I am familiar with using two conditions, but is there a way to use more than two without getting a syntax error? <option {{ change === 1 ? &apos ...

Utilizing express-session in TypeScript: Incorporating user information into the session

Hey, I'm currently working on implementing express-session and connect-mongodb-session in my TypeScript Express/Node API. My goal is to use express-session to create a cookie for logged-in users and automatically persist that cookie to MongoDB. Howeve ...

Is it possible to use TypeScript or Angular to disable or remove arrow key navigation from a PrimeNG Table programmatically?

Is there a way to programmatically prevent left and right arrow key navigation in a PrimeNG Table with cell editing, without the need to modify the Table component source code? You can check out an example here: Angular Primeng Tableedit Demo code. I mana ...

Angular is set up to showcase every single image that is stored within an array

I am having trouble displaying the images from the "image_url" array using a for loop. The images are not showing up as expected. Here is the content of the array: image_url: [ 0: "https://xyz/16183424594601618342458.5021539.jpg" 1: "https://xyz/1618342459 ...

Achieving a draggable object to land on a designated target

Before you jump to conclusions based on the title, let me clarify that I am not referring to jQuery UI draggable. Instead, I am discussing a plugin that I am currently developing for the community. The goal of my plugin is to create a designated target fea ...

Unable to transfer variable from a function to the test in Protractor

Currently, I am working on a test to verify the amount of gold in my possession. The test is being conducted using TypeScript and Protractor. Within this testing scenario, I have a method named GetAmountOfChips: public static GetAmountOfChips(): PromiseL ...