ionic2:API 响应数据未定义?



我正在使用ionic2,我想向api服务器发出登录请求,但我有响应=>undefined这是提供程序中的代码:

loginUser(email, password, macId, token) {
let userObject = {
"email": email,
"password": password,
"mac" : macId,
"token" : token
}
var headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Access-Control-Allow-Origin', '*');
console.log('object: ',userObject);
return this.http.post(this.loginUrl, userObject, {headers:headers})
.map((response: Response) => response.json())    
}

这是login page中的代码:

loginUser(email,password) {
console.log('email: ',email,'password: ',password);
if(!this.loginForm.valid){
this.submitAttempt = true;
} else {
this.submitAttempt = false;
this.deviceInfo.macId = this.device.uuid;
this.fcm.getToken().then(token=>{
this.token = token;
});
this.userProvider.loginUser(email,password,this.deviceInfo.macId,this.token)
.subscribe(data=> {
alert("data is "+data);
},
(err)=>{
alert("err"+err);
}
)

}

输出应为:

{
msg : "SyGgTmNHxJcZFYJu6RootUHAqzdkhPNzsTGJHipeBZQSN8nHdbHga4gQ3jENesNPsK5tdtGKlmUa5g3cIVDO4ZqqENd5uPizwgWkq6z3CyUXAhyns8PTnNPwax7lgKRiY7I67qmiPCpZdwu2Kh5v7U"
}

但实际输出:

data: "undefined"

我该怎么办?

你不需要map它,只需returnthis.http.postuserProvider函数中返回的promise,并使用.then()调用它来获取数据:

loginUser(email, password, macId, token) {
let userObject = {
"email": email,
"password": password,
"mac" : macId,
"token" : token
}
var headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Access-Control-Allow-Origin', '*');
console.log('object: ',userObject);
return this.http.post(this.loginUrl, userObject, {headers:headers});  
}

和。。。

loginUser(email,password) {
console.log('email: ',email,'password: ',password);
if(!this.loginForm.valid){
this.submitAttempt = true;
} else {
this.submitAttempt = false;
this.deviceInfo.macId = this.device.uuid;
this.fcm.getToken().then(token=>{
this.token = token;
});
this.userProvider.loginUser(email,password,this.deviceInfo.macId,this.token)
.then(data=> {
alert("data is "+data);
},
(err)=>{
alert("err"+err);
}
)
}

相关内容

  • 没有找到相关文章

最新更新