Angular 4中的Observable调用可以像jquery的sync ajax方式吗?
问题描述:
我有一些业务逻辑函数来调用,其中有一个逻辑,必须使用HttpGet,我必须等到它返回结果contiune,如果我使用jquery的ajax可以简单地做到这一切,不知道是否Observable也有类似的方法?Angular 4中的Observable调用可以像jquery的sync ajax方式吗?
我希望resut是:
- 约翰
- 安迪
但现在的结果是只显示安迪 :(
function main(){
/*
I have more than 70 sharing rules to deal with different Logic
(e.g. getAge , getSomthing...), in order to simplify the problem ,
I only list two rules as a demonstration
*/
methods = [
getNameFromServer,
getSomeOneName
];
const result = [];
methods.forEach(method => {
method(result);
})
console.log(result);
}
function getNameFromServer(result){
Rx.Observable.of('John')
.delay(1000)
.subscribe(name => {
console.log('now async get name , but I need it will be sync')
result.push(name)
});
// can I use sync Ajax like jquery's code?
// $.ajax({
// ... ,
// async: false
// })
// .done(response => result.push(response.xxx))
}
function getSomeOneName(result){
result.push('Andy');
}
// execute
main();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.0.1/Rx.js"></script>
</head>
<body>
</body>
</html>
答
在任意现代浏览器可以使用async
/await
得到同步行为。你必须:
- 声明你
main
为async
- 更换
forEach
与for
...of
(回调不能很好地与await
工作) - 将您
Observable
到Promise
使其awaitable,然后返回它 - 替换
subscribe
与do
。你仍然会得到副作用,但do
返回观察值,所以你可以立即连锁toPromise
。观察者由toPromise
代码自动订阅将是:
async function main(){
methods = [
getNameFromServer,
getSomeOneName
];
const result = [];
for (let method of methods) {
await method(result);
}
console.log(result);
}
function getNameFromServer(result){
return Rx.Observable.of('John')
.delay(1000)
.do(name => {
console.log('now async get name , but I need it will be sync')
result.push(name)
})
.toPromise();
// can I use sync Ajax like jquery's code?
// $.ajax({
// ... ,
// async: false
// })
// .done(response => result.push(response.xxx))
}
function getSomeOneName(result){
result.push('Andy');
}
// execute
main();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.0.1/Rx.js"></script>
</head>
<body>
</body>
</html>
+0
感谢您的回复,这是我想要的,如果我需要支持IE 9,不知道你有什么想法? –
+0
不,在IE中是不可能的,甚至不是10.只能从Edge开始。 –
而不是'异步:FALSE' - > [如何返回从一个异步调用的响应? ](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Andreas
your console.log(result);在observable将John添加到结果数组之前正在运行。 console.log(result)after result.push(name)after your observable – LLai
因为在console.log(result)之后完成了observable; – aimprogman