typescript 角度如何等待订阅
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48185502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
angular how to await subscribe
提问by Jon Doe
I am newbie regarding angular applications. I don't understand exactly how subscribe works. My problem in this case is that I don't understand why the console.log("B") is executed before the console.log("A")...obviously with the result of an empty array (see the attached image "console"). I tried to put all the code in a function and tried with async/await to wait for that function but doesn't work and i don't understand why.
我是角度应用程序的新手。我不明白订阅是如何工作的。在这种情况下我的问题是我不明白为什么在 console.log("A") 之前执行 console.log("B") ......显然是空数组的结果(见附图“安慰”)。我试图将所有代码放在一个函数中,并尝试使用 async/await 等待该函数,但不起作用,我不明白为什么。
What is the best way in this case to wait for a subscription?
在这种情况下等待订阅的最佳方式是什么?
The console.log("B") must be executed after the console.log("A").
console.log("B") 必须在 console.log("A") 之后执行。
Thank you
谢谢
this._roleService.getRoleTypes(this.token).subscribe(
response => {
if(response.status != "error" && response.code != 400){
let _roleTypes:Array<RoleType> = new Array<RoleType>();
_roleTypes = new Array<RoleType>();
response.data.forEach(rt => {
let roleType:RoleType = new RoleType(
rt.id,
rt.name
);
_roleTypes.push(roleType);
});
console.log("A");
console.log(_roleTypes);
this.roleTypes = _roleTypes;
}
else{
this._loginService.destroySession();
}
},error => {
this.errorMessage = <any>error;
if(this.errorMessage != null){
console.log(this.errorMessage);
alert("Petition Error");
}
}
);
console.log("B");
console.log(this.roleTypes);
采纳答案by Kapcash
As you may know, subscriptions are used to handle async method call. Thus, the code inside the subscribe() method is executed only when the async method return its result (after a http call for instance).
您可能知道,订阅用于处理异步方法调用。因此,仅当异步方法返回其结果(例如在 http 调用之后)时,才会执行 subscribe() 方法中的代码。
While waiting for the async response, the program continues and execute the following code. That's the goal of async calls!
在等待异步响应的同时,程序继续执行以下代码。这就是异步调用的目标!
That's why your console.log('B')
is executed before your console.log('A')
.
这就是为什么你console.log('B')
的在你的console.log('A')
.
Here is an example:
下面是一个例子:
this.myservice.asyncCall().subscribe( (result) => {
// wait for the async response
console.log('I get some data from asyncCall()');
});
// sync code executed, even if the previous async call doesn't respond anything
console.log('Code executed after the subscription. But not waiting for it to respond');
If you want you're console.log('B')
, you have to move it into your subscription function (after the else statement). You can also call a method from that location, depending on the purpose you're looking for.
如果你想要你console.log('B')
,你必须把它移到你的订阅函数中(在 else 语句之后)。您还可以从该位置调用方法,具体取决于您要查找的目的。
You may take a look at the .map()
method as well. This allows you to edit the retrieved response before you handle it in the subscribe method (to add it some data, transform it, log or anything).
你也可以看看.map()
方法。这允许您在 subscribe 方法中处理检索到的响应之前对其进行编辑(添加一些数据、转换它、记录或其他任何内容)。
回答by Charlie
You should use async/await if you need synchronous execution of your code. Wrap your subscribe code in a function that returns a promise.
如果您需要同步执行代码,则应使用 async/await。将您的订阅代码包装在一个返回承诺的函数中。
async getRolestypes(): Promise<Array<RoleType>> {
return new Promise((resolve, reject) => {
this._roleService.getRoleTypes(this.token).subscribe(
response => {
if(response.status != "error" && response.code != 400){
let _roleTypes:Array<RoleType> = new Array<RoleType>();
_roleTypes = new Array<RoleType>();
response.data.forEach(rt => {
let roleType:RoleType = new RoleType(
rt.id,
rt.name
);
_roleTypes.push(roleType);
});
console.log("A");
console.log(_roleTypes);
resolve(_roleTypes);
}
else{
this._loginService.destroySession();
reject('not a good response')
}
},error => {
this.errorMessage = <any>error;
if(this.errorMessage != null){
reject(this.errorMessage);
}
}
);
})
}
this.roleTypes = await getRolestypes();
console.log(this.roleTypes);
回答by Furqan Shaikh
subscribe is executed asynchronously. In your case, subscribe will execute and then console.log('B') will get executed after that. When at a later point of time, the Observable posts the response (based on success/error), corresponding success/error callback will be invoked. so you can handle console.log('B') in in the success callback
subscribe 是异步执行的。在您的情况下, subscribe 将执行,然后 console.log('B') 将在此之后执行。稍后,当 Observable 发布响应(基于成功/错误)时,将调用相应的成功/错误回调。所以你可以在成功回调中处理 console.log('B')