Angular 无法从组件向服务传递数据

Angular 无法从组件向服务传递数据,angular,typescript,Angular,Typescript,我试图将参数传递给服务中定义的函数。参数总是未定义的 login.component.ts import { Component, OnInit } from '@angular/core'; import { AuthenticationService } from '../authentication.service'; @Component({ selector: 'app-login', templateUrl: './login.component.html',

我试图将参数传递给服务中定义的函数。参数总是
未定义的

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.')
    );

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

@Injectable()
export class AuthenticationService {

constructor() { }

login(credentials) {

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

}
authentication.service.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.')
    );

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

@Injectable()
export class AuthenticationService {

constructor() { }

login(credentials) {

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

}

我遗漏了什么?

您正在完美地传递数据,但问题是您使用类型
{username:'',password:''声明了变量
凭据
,您没有给它赋值,这就是它未定义的原因<代码>:
将类型分配给变量,
=
分配值。这就是你要找的:

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

啊。我用了
而不是
=
。谢谢Stefan。我应该删除这个问题吗?@KabirRoy这是真的,伙计,别担心。我看不出有什么理由删除它,但如果您愿意,您可以选择删除它。:-)