我在角度2应用程序中有一个服务和一个组件,我在服务中得到响应并且能够登录到控制台但它在组件中显示未定义。怎么了我在这里做错了?任何人都可以指出错误。 提前致谢
服务
import { Injectable } from '@angular/core'
import { Http, Response,Headers } from '@angular/http'
import { Observable } from 'rxjs/Observable'
import "rxjs/add/operator/map"
import "rxjs/add/operator/catch"
import "rxjs/add/Observable/throw"
@Injectable()
export class LoginService {
public logResult;
private _url = "http://localhost:53798/api/Login?uname=abcd&pass=1"
constructor(private _http: Http) { }
getEmployees(userID:string,passWord:string) : Observable<boolean>{
return this._http.get(this._url).map((response: Response) =>
{
let logResult= response.json();
logResult.forEach(re=>{
if(re.LoginResult=="Success")
{
console.log('Success');//this is being written to console
return<boolean> true;
}
else{
console.log('fail');
return<boolean> false;
}
})
}).catch(this._errorHandler);
}
_errorHandler(error: Response) {
console.log(error);
return Observable.throw(error || "Server not Found")
}
}
Componet:
ValidateLogin(){
this._loginService.getEmployees(this.loginForm.value.UserId,this.loginForm.value.password)
.subscribe(resLoginData => {
console.log(resLoginData);//resLoginData is undefined
if(resLoginData===true)
{
console.log('Success');
this.router.navigateByUrl('/Home');}
else{
console.log('Fail');
this.router.navigateByUrl('/Login');
}
resLoginError => this.errorMsg = resLoginError})
}
}
答案 0 :(得分:2)
forEach
阻止在return
声明中停止。
let logResult= response.json().data;
let result = false;
logResult.forEach(re=>{
if(re.LoginResult=="Success")
{
// console.log('Success');//this is being written to console
result = true;
}
else{
// console.log('fail');
result false;
}
});
return result; // return the true result out of forEach.
另外,您应该将let logResult= response.json();
更改为let logResult= response.json().data;
,因为http的方法会以这种方式返回数据。
答案 1 :(得分:0)
您是否在应用中安装了rxjs和zone-js
import { Injectable } from "@angular/core";
import { Http, Response, Headers, RequestOptions, URLSearchParams } from "@angular/http";
import { Observable } from "rxjs/Observable";
import "rxjs/Rx";
@Injectable()
export class LoginService {
public logResult;
private _url = "http://localhost:53798/api/Login?uname=abcd&pass=1"
constructor(private _http: Http) { }
getEmployees(userID:string,passWord:string) : Observable<boolean>{
return this._http.get(this._url).map((response: Response) =>
{
let logResult= response.json();
logResult.forEach(re=>{
if(re.LoginResult=="Success")
{
console.log('Success');//this is being written to console
return true;
}
else{
console.log('fail');
return false;
}
})
}).catch(this._errorHandler);
}
_errorHandler(error: Response) {
console.log(error);
return Observable.throw(error || "Server not Found")
}
}