如何在 Angular2/Typescript 中调试 Observable 值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40256541/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:57:43  来源:igfitidea点击:

How to debug Observable values in Angular2 / Typescript?

angulartypescriptrxjsobservablerxjs5

提问by Ilya Chernomordik

I have followed the tutorial for angular 2 and have a search functionality that renders a list of heroes asynchronously.

我遵循了 angular 2 的教程,并且有一个搜索功能,可以异步呈现英雄列表。

<div *ngFor="let hero of heroes | async">
    {{hero.name}}
</div>

In the component I have observable heroes:

在组件中,我有可观察到的英雄:

heroes: Observable<Hero[]>;

Now I have implemented similar functionality in my application by I don't see anything and I don't see any errors either. I opened the debugger in Chrome and tried to check the value of heroes, but it's just some Observable wrapper of course.

现在我在我的应用程序中实现了类似的功能,但我什么也没看到,也没有看到任何错误。我在 Chrome 中打开调试器并尝试检查 hero 的值,但它当然只是一些 Observable 包装器。

Is there any way to see the current/last or some value in the debugger or maybe there is some other technique to debug such issues?

有没有办法在调试器中查看当前/最后一个值或某个值,或者可能有其他一些技术来调试此类问题?

回答by Harry

In RxJS v6+, the tap()operator has replaced do(). So it will look more like this now:

在 RxJS v6+ 中,tap()操作符取代了do(). 所以它现在看起来更像这样:

someObservable$.pipe(
  map(x => x.whatever),
  tap(whatever => console.log(whatever)),
)

回答by Meir

First of all, if you're using typescript consider:

首先,如果您使用打字稿,请考虑:

heroes: Observable<Array<Hero>>;

If you want to print it, you can simply add in your code:

如果你想打印它,你可以简单地添加你的代码:

heroes.subscribe((v) => console.log('got new heroes list: ', v));

回答by tibbus

You can use the do()operator EX :

您可以使用do()运算符 EX :

this.http
        .get('someUrl', options)
        .map(res => res.json())
        .do(
            data => {
                console.log(data);
            },
            error => {
                console.log(error)
            }
        )

If nothing happens inside the do() functions it means you are not subscribed to that observable, remember that observables are waiting for a subscription to start doing something.

如果 do() 函数内部没有发生任何事情,则意味着您没有订阅该 observable,请记住,observable 正在等待订阅开始做某事。

回答by Eric Simonton

If you want to do some console.logdebugging, I wrote a little helper logValues()in s-rxjs-utils. You can use it like this (from the docs):

如果你想做一些console.log调试,我logValues()s-rxjs-utils. 您可以像这样使用它(来自文档):

of(1, 2).pipe(logValues()).subscribe();
// prints using console.log:
// [value] 1
// [value] 2
// [complete]

You can also pass it a string to print along with the values, and specify the log level.

您还可以传递一个字符串与值一起打印,并指定日志级别。