Ensuring the accuracy of forms using third-party verification services

While working on an Angular form validation using an external service, I encountered a

cannot read property of undefined
error.

The component contains a simple form setup:

this.myForm = this.fb.group({
  username: ['', [this.validator.username]],
});

Within this, the username method is being utilized:

@Injectable()
export class ValidatorService {
  constructor(private auth: AuthService) {}
  username(input: FormControl): {[key: string]: any} {
    return { userInvalid: this.auth.validate(input.value) };
  }
}

The ValidatorService makes use of a method that checks with the server to validate the username:

@Injectable()
export class AuthService {
  validate(username: string): boolean {
    return username !== 'demo';
  }
}

However, an error has surfaced:

Cannot read property 'auth' of undefined
. Any insights or solutions for this issue?

Live demo

Answer №1

username function is being called as a method instead of a function of ValidationService, causing you to lose the context of this.

Using the Function.prototype.bind method can solve this issue:

username: ['', [this.validator.username.bind(this.validator)]],

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

Tips for ensuring the server only responds after receiving a message from the client in a UDP Pinger system using sockets

I am in the process of developing a UDP pinger application. The objective is for the client to send a message (Ping) and receive pong back 10 times. However, the challenge lies in sending the messages one at a time instead of all together simultaneously. T ...

Accordion Tuning - The Pro and Cons

Here is a functional accordion that I've implemented, you can view it here This is the JavaScript code I am using: $(document).ready(function ($) { $('#accordion').find('.accordion-toggle').click(function () { //Expa ...

Creating conditional keys using the Zod library based on the value of another key

Incorporating the TMDB API into my project, I am making an effort to enhance type safety by reinforcing some of the TypeScript concepts I am learning. To achieve this, I am utilizing Zod to define the structure of the data returned by the API. Upon invest ...

Is there a way for me to determine the specific link that I have clicked on

I am implementing a table where users can edit the columns. Each cell contains an <a> tag that triggers a modal to change the value in the database and refresh the page. The issue I'm facing is that once the modal appears, the code doesn't ...

Is there a way to automatically change specific characters as a user types in an input field?

I'm facing an issue with replacing some characters dynamically. The goal is to ensure that user-input text is URL-friendly for constructing a URL: function slugify(string) { const a = "àáâäæãåāăąçćčđďèéêëēėęěğǵḧîïí ...

Display or conceal a YouTube video with a click

Q1) Is it possible to use JQuery on page load to detect the file name of an image and then dynamically position it on the page with CSS? Q2) What is the most efficient way to achieve this without embedding iframe code inside a specific div.icon element? ...

What is the best way to access a reference to the xgrid component in @material-ui?

Is there a way to obtain a global reference to the xgrid component in order to interact with it from other parts of the page? The current code snippet only returns a reference tied to the html div tag it is used in, and does not allow access to the compo ...

Obtaining the latest state within the existing handler

In my React application, I have a handler that shuffles the state entry data: state = { data:[1,2,3,4,5] }; public handleShuffle = () => { const current = this.state.data; const shuffled = current .map((a: any) => [Math.random() ...

Why is a dispatch call in React-Redux being executed before another?

My Pokedex is functioning properly, but I have encountered an issue with React-Redux Dev Tools: The function "getPokemonsInfo" is being called before "getPokemonsUrls", however, "getPokemonsInfo" should only be triggered when a property in the state chang ...

How can you style a two-item list in Material-UI React to display the items side by side?

I have a list that contains two items: 'label' and 'value'. This is the current layout: https://i.stack.imgur.com/HufX7.png How can I rearrange the items on the right to be positioned next to the label on the left? https://i.stack.im ...

Functionality of the Parameters Object

As I transition from using the params hash in Rails to learning Node/Express, I find myself confused about how it all works. The Express.js documentation provides some insight: 'This property is an array containing properties mapped to the named rout ...

The Ajax response fails to update my viewmodel

I have a value and a list that I need to update from within an Ajax callback. After retrieving a fresh value using .get(), I try to assign it to my view model's property, but the UI does not refresh properly. Below is the code snippet: function Searc ...

Creating interactive tabs within the HTML document with AngularJS

Trying to customize the tab layout on my HTML page and I have a code similar to this: <form name="requestForm"> <div class="form-group col-md-6 md-padding"> <div class="text-primary"> <h3>Create Request</h3> ...

Deciphering the intricacies of the http request

I encountered an issue while trying to send a POST request using jQuery AJAX. Upon making the request, I received the following error: XMLHttpRequest cannot load. Response for preflight has invalid HTTP status code 403 Now, I am unsure if the mistake i ...

Ways to extract X-Total-Count from json-server using Angular's http.get function

Currently, I am utilizing json-server on localhost:3000. The setup is running smoothly, and I can fetch data in Angular through http.get. My objective is to access the response header X-Total-Count within the Angular .subscribe method. However, I am unab ...

The detection of my query parameters is not working as expected

Creating an Angular application that dynamically loads a different login page based on the "groupId" set in the URL is my current challenge. The approach involves sending each client a unique URL containing a specific "groupId" parameter. A template is the ...

Incorporating JSON data into an array using d3

I'm currently working on mapping JSON data to an array variable in d3. Below is the JSON I am using: [ { "Impressions": "273909", "Clicks": "648", "CPM": 4.6388278388278, "Cost": 1266.4, "CPC": 1.9543209876543, "Campaign": "C ...

Experiencing difficulties in transmitting multipart form data from React to Express Js accurately

I am facing an issue with uploading files using Dropzone and sending them to a Java backend API from React JS. In this scenario, React sends the document to Express backend where some keys are added before forwarding the final form data to the Java endpoin ...

Update Refresh Token within Interceptor prior to sending request

I'm stuck on this problem and could use some guidance. My goal is to refresh a user's access token when it is close to expiration. The authService.isUserLoggedIn() function returns a promise that checks if the user is logged in. If not, the user ...

What could be the issue with trying to bind an event handler in this manner?

I'm having some trouble binding an event handler with jQuery: $(document).ready(function () { var newsScrollerForPage = new NewsScroller(); newsScrollerForPage.init(); $('#scroller-left-a').bind('on ...