我正在学习角度并练习一些项目。我有2项服务:
现在我在组件中称为 Component.ts
onLoginTry(loginForm: NgForm){
this.accountService.loginUser(loginForm.value.email, loginForm.value.password);
}
帐户服务
loginUser(Email: String, Password: String){
console.log("login try: "+Email+" "+Password);
this.webService.loginUser({Email: Email, Password: Password})
.subscribe(
data=>{
//console.log(data);
console.log("SUBSCRIBE");
return data;
}
);
console.log("LOGIN ACCOUNT SERVICE");
}
网络服务
loginUser(user: any){
const body = JSON.stringify(user);
const headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post('http://'+this.web_url+':'+this.web_port+'/api/User_login', body, {
headers: headers
})
.map((data: Response) =>data.json());
}
问题: 我想将帐户服务中的loginUser数据返回到组件,但是当我这样做时,在控制台日志中返回undefined
编辑:我在帐户服务功能中获取数据值,但我想将其发送到组件。
答案 0 :(得分:1)
您希望从服务器获取数据到组件,因此只需订阅它,如下所示:
Component.ts
onLoginTry(loginForm: NgForm) {
this.accountService.loginUser(loginForm.value.email, loginForm.value.password).subscribe(data => console.log(data));
}
<强> AccountService.ts 强>
loginUser(Email: string, Password: string): Observable<any> {
return this.webService.loginUser({Email: Email, Password: Password});
}
网络服务
loginUser(user: any): Observable<any> {
const body = JSON.stringify(user);
const headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post('http://'+this.web_url+':'+this.web_port+'/api/User_login', body, { headers }).map((data: Response) => data.json());
}