Kabir Roy Kabir Roy - 1 month ago 7
TypeScript Question

Unable to pass data to service from component

I am trying to pass a parameter to a function defined in a service. The parameter is always

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

}


What am I missing?

Answer

You are passing data perfectly, but the problem is you declared variable credentials with type { username: '', password: '' };, you didn't assign value to it, which is why it is undefined. : assigns type to variable, = assigns value. This is what you're looking for:

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