简体   繁体   中英

ionic2: API response data undefined?

I'm using ionic2 , I want to make login request to api server, but I have response => undefined this is the code in provider:

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())    
  }

and this is the code in 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);
   }
 )


}

the output should be:

{
  msg : "SyGgTmNHxJcZFYJu6RootUHAqzdkhPNzsTGJHipeBZQSN8nHdbHga4gQ3jENesNPsK5tdtGKlmUa5g3cIVDO4ZqqENd5uPizwgWkq6z3CyUXAhyns8PTnNPwax7lgKRiY7I67qmiPCpZdwu2Kh5v7U"
}

but the actual output:

data: "undefined"

what should I do?

You don't need to map it, just return the promise that is returned by this.http.post in your userProvider function and use .then() where you are calling it to get the data:

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});  
}

and...

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);
       }
     )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM