角度如何等待订阅 [英] angular how to await subscribe

查看:36
本文介绍了角度如何等待订阅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Angular 应用程序的新手.我不明白 subscribe 是如何工作的.我目前的阻碍是我不明白为什么 console.log("B")console.log("A") 之前执行,因此呈现空数组的结果(请参阅 console 输出的链接).

I am newbie regarding Angular applications. I don't understand exactly how subscribe works. My current blocker is that I don't understand why the console.log("B") is executed before the console.log("A"), consequently presenting the result of an empty array (see the links to console output).

我尝试将所有代码放入一个带有 async/await 的函数中以等待该函数.我不明白为什么它不起作用.

I tried to put all the code in a function with async/await to wait for the function. I don't understand why it doesn't work.

在这种情况下等待订阅的最佳方式是什么?

What is the best way in this case to wait for a subscription?

console.log(B") 必须在 console.log(A") 之后执行.

The console.log("B") must be executed after the console.log("A").

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);

  • 代码
  • 控制台
  • 推荐答案

    您可能知道,订阅用于处理异步方法调用.因此,仅当异步方法返回其结果(例如在 http 调用之后)时,才会执行 subscribe() 方法中的代码.

    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).

    在等待异步响应的同时,程序继续执行以下代码.这就是异步调用的目标!

    While waiting for the async response, the program continues and execute the following code. That's the goal of async calls!

    这就是为什么您的 console.log('B') 在您的 console.log('A') 之前执行.

    That's why your console.log('B') is executed before your console.log('A').

    这是一个例子:

    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');
    

    如果你希望你是 console.log('B'),你必须把它移到你的订阅函数中(在 else 语句之后).您还可以从该位置调用方法,具体取决于您要查找的用途.

    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.

    你可以看看.map() 方法也是如此.这允许您在 subscribe 方法中处理检索到的响应之前对其进行编辑(添加一些数据、转换它、记录或其他任何东西).

    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).

    这篇关于角度如何等待订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆