I've a service with an authenticate function -
authenticate(username: string, password: string) {
let ret;
let packet = JSON.stringify({
username: username,
password: password
});
let headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.post('http://localhost:5000/api/authenticate/', packet, {
headers: headers
})
.map(res => res.json())
.subscribe(
data => {
// put return data into ret
ret = data.token;
},
err => console.log(err),
() => {
// this works!
console.log(ret);
}
);
// get's returned before I put data into it
return ret;
}
So if I call the authenticate function console.log(authenticate('a', 'b'));, it logs undefined since the ret variable is returned before the subscribe function can put the data into it. How can I return the http response data from authenticate function? I've never done any reactive programming with RxJS before and that's what angular 2 seems to be using.
PS. Is there any decent CSP solution for javascript like go channels or core.async?
subscribeis executed before you return, but it's async. I don't know what the AngJS "way" is, but you'd either need a callback, or an observer, or whatever event stream mechanism RxJS uses.