Ionic 2 function return problem


#1

i am calling a function like this…

console.log("print 3 "+this.getUsername(this.email));

getUsername(email){

var link='https://xxxxx.php?action=get_reviewer&email='+email;
var username:string;
var obj:any;
this.http.get(link).map(res => res.json()).subscribe(data => {
  obj = data;
  username = obj['userName'];
  console.log("print 1 "+username);

});
console.log("print 2 "+username);
return username;

}

and i got the console log like this

2017-05-16 00:14:54.405171+0800 Learning[12494:3407115] print 2 undefined
2017-05-16 00:14:54.405238+0800 Learning[12494:3407115] print 3 undefined
2017-05-16 00:14:54.511347+0800 Learning[12494:3407115] print 1 Nick

i can’t get the result from function getUsername and also the log order is wrong, is there any reason?


#2

Yes, you’re performing an async operation and then outside of the async you’re trying to get the results immediately, that won’t work. I suggest you move your this.http.get into a service, map your result, return that and then subscribe to it.

Also, don’t use var but get used to use let instead. The block scoping solves a lot of issues that exist with var. Don’t make use of any unless absolutely necessary. It makes your code easier to debug. In this post you can see an example about how you should handle subscribables inside your class.