2016-10-22 13 views
1

サービスで定義された関数にパラメータを渡そうとしています。パラメータは常に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 

} 

私は何をしないのですか?

答えて

2

データを完全に渡していますが、変数credentialsがタイプ{ username: '', password: '' };と宣言されていて、値を割り当てられていないため、undefinedです。 :はタイプを変数に割り当て、=は値を割り当てます。これはあなたが探しているものです:

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

私は '='の代わりに ':'を使いました。ステファンありがとう。質問を削除する必要がありますか? –

+0

@KabirRoyそれは男が起こる、心配しないでください。私はそれを削除する理由はありませんが、あなたが望むなら削除することができます。 :-) –

関連する問題