【发布时间】:2016-07-20 11:03:26
【问题描述】:
我有一个具有身份验证功能的服务 -
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;
}
所以如果我调用验证函数console.log(authenticate('a', 'b'));,它会记录undefined,因为ret 变量在订阅函数可以将数据放入其中之前返回。如何从身份验证函数返回 http 响应数据?我以前从来没有用 RxJS 做过任何反应式编程,这就是 angular 2 似乎正在使用的东西。
PS。有没有像 go channels 或 core.async 这样像样的 JavaScript 的 CSP 解决方案?
【问题讨论】:
-
这并不是 async 或 RxJs 的真正工作方式;您不会从异步函数返回数据。
-
我想了这么多,因为在我返回 ret 变量后 subscribe 被执行。关于在处理 RxJS 时如何返回数据的任何想法?
-
你可以创建另一个方法,比如 this.authenticateFinished(ret) { console.log(ret); // 和其他任何东西 } 然后从 data => {} 调用它
-
好吧,
subscribe在您返回之前执行,但它是异步的。我不知道 AngJS 的“方式”是什么,但你要么需要回调,要么需要观察者,或者 RxJS 使用的任何事件流机制。
标签: angular typescript asynchronous rxjs