Having difficulty transferring information from the component to the service

I am having trouble passing a parameter to a function that is defined in a service. No matter what I try, the parameter always ends up being undefined.

login.component.ts

import { Component, OnInit } from '@angular/core';

import { AuthenticationService } from '../authentication.service';

@Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.css'],
    providers: [AuthenticationService]
})
export class LoginComponent implements OnInit {

credentials: {
    username: '',
    password: ''
};

constructor(private _authenticationService: AuthenticationService) {}

ngOnInit() { }

login() {

    this._authenticationService.login(this.credentials).subscribe(
        response => console.log(response),
        error => console.log(error),
        () => console.log('Done.')
    );

}

authentication.service.ts

import { Http } from '@angular/http';
import { Injectable } from '@angular/core';

@Injectable()
export class AuthenticationService {

constructor() { }

login(credentials) {

    console.log(credentials); // This is undefined

}

Can anyone help me figure out what I am missing?

Answer №1

The issue lies in the fact that although you are correctly passing data, the variable credentials was declared with the type { username: '', password: '' };, but no value was assigned to it, resulting in it being undefined. The colon : is used to assign a type to a variable, while the equal sign = is used to assign a value. Below is the correct syntax you need:

credentials: any = {
    username: '',
    password: ''
};

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

Angular throws an error when attempting to use localStorage as it is not defined in the environment

Encountering an issue while running this code, as the error message "localStorage is not defined" keeps popping up. Additionally, when it comes to todos != Todo[], why can't we simply set it to null instead of using the exclamation mark? import { Comp ...

Can you explain the execution process of this Http.post method and provide details about the code path it follows

As I delve into the world of web development, one aspect that has me stumped is the functionality of the Http.post section within a project I stumbled upon on GitHub. Specifically, this pertains to an ExpressJS with Typescript repository I came across. So, ...

The input element's value property updates only once

Whenever I input a number greater than 1 into the input field, the value automatically changes to 1 due to validation. Oddly enough, this only seems to work for the first number entered. For example, if I type in 11, the input value remains as it is instea ...

Encountering a tuple type TypeScript error with a spread argument is far too frequent an occurrence

Encountering this error is becoming a frequent occurrence for me, and I am currently unable to resolve it. src/graphics.ts:105:55 - error TS2556: A spread argument must either have a tuple type or be passed to a rest parameter. 105 _queue.forEach((_ ...

No matter the circumstances, the "Unexpected end of form" error consistently appears when attempting to upload files in Express

I'm facing a challenge in implementing a file upload API endpoint for my Express+no-stress+Typescript application. Initially, I attempted to use the express-fileupload library, but I quickly realized that it didn't integrate well with Typescript ...

What is the proper way to implement Firebase getDoc in Vue with vue-concurrency?

I am currently in the process of developing a TypeScript Vue composable that utilizes Firebase and the vue-concurrency library. According to the documentation, I need to explicitly type any intermediate values that are yielded. I am facing a challenge wh ...

Matching list symbols in regular expressions (Angular 2)

I have been attempting to find a solution for matching a list of symbols using regex, but I keep encountering errors in the result. The symbol list includes: !@#$+*{}?<>&’”[]=%^ if (text.match('^[\[\]\!\"\#&bs ...

Steps for sending angular form data to a .Net backend that requires an autoincrement id:

When trying to insert data into an SQL database through a .Net API endpoint, I encountered an issue with the request body specifying that the ID is auto-incremental. Status 500: Cannot insert explicit value for identity column in table 'StockFeed&ap ...

Applying ngClass to a row in an Angular material table

Is there a way I can utilize the select-option in an Angular select element to alter the css-class of a specific row within an Angular Material table? I have successfully implemented my selection functionality, where I am able to mark a planet as "selecte ...

Implementing an All-Routes-Except-One CanActivate guard in Angular2

In order to group routes within a module, I am aware that it can be done like this: canActivate: [AuthGuard], children: [ { path: '', children: [ { path: 'crises', component: ManageCrisesComponent }, ...

Could there be an issue with the way I've implemented my setInterval function?

I am currently in the process of developing a stopwatch feature using React Native and implementing the setInterval function to increase a counter and update the state accordingly: Play Function (triggered upon pressing the play button) const [isRunning ...

What steps should I take to export a function from a React functional component in order to create a reusable library?

Currently, I am in the midst of developing a React component library and one of my components contains a function that I want to export. The purpose of the addParticle function is to enable users of the library to dynamically insert particles into a cont ...

Struggling to integrate a JavaScript sdk with an Angular2 application due to missing dependencies

I've been struggling to incorporate the Magic: The Gathering SDK library into my Angular2 application. I've tried various methods, but nothing seems to work seamlessly. When I attempt to import the library using TypeScript like this: import { } ...

The AOT Compilation error occurs in Angular2 RC6 when trying to call the function RouterModule.forChild(ROUTES) which is not supported

Operating Environment: Windows 10, IntelliJ 2016.2, node Angular Version: 2.0.0-rc.6 Language: [all | TypeScript X.X | ES6/7 | ES5] Typescript ES6 Node (for Ahead of Time Compilation issues): node --version = Node 4.4.7, NPM 3.10.6 The AOT com ...

Difficulties in Networking Requests Following Event Emitter Notification in an Angular Application

Within my Angular application, a network request is sent to retrieve filtered data based on user-selected filters. The function responsible for handling the filter values and executing the request is outlined as follows: public onFilterReceived(values) { ...

Typescript Next.js Project with Custom Link Button Type Definition

I have a project that includes a custom Button component and a NextLink wrapper. I want to merge these two components for organization purposes, but when I combine the props for each, I encounter an issue with spreading the rest in the prop destructuring s ...

When I click on a tab section to expand it, the carat arrows all point upwards. Only the arrows corresponding to the selected section should

click here for imageIt appears that there are four tabs, each with a click function on the carat icon. When I expand one tab, all carats point upwards instead of only the selected one appearing. accountSelection(account) { if (!this.selectedAccoun ...

Can data be transmitted in Angular without using a selector?

I am facing a challenge in sending data from a child component to its parent. The parent component's HTML code does not utilize the child's selector, as it is within a dialog of Angular Material and only uses "MatDialogRef" and "dialog.open()". T ...

A proposal for implementing constructor parameter properties in ECMAScript

TypeScript provides a convenient syntax for constructor parameter properties, allowing you to write code like this: constructor(a, public b, private _c) {} This is essentially shorthand for the following code: constructor(a, b, _c) { this.b = b; thi ...

The absence of a `require` definition in Typescript combined with daisyui

Considering using typescript with react and daisyUI (a tailwindCSS component). Just a heads up, I'm currently utilizing vite In my ts.config file, I've specified node as moduleResolution Encountering an error in the tailwind config stating &apo ...