2

I can display a value produced by an Observable using {status_async | async} in html.

However, how can I test whether this Observable is equal to something?

Specifically, I'd like to use it to assign a class:

<div [ngClass]="{'has-danger': status_async == 'created before'}">
    <input type="text">
</div>

I discovered that I can use:

<div [ngClass]="{'has-danger': (status_async | async) == 'created before'}">

But then the issue becomes that I have used async twice (here and for displaying the value).

As I'm checking the status of a succesful creation, ironically after the second async the value changes to 'created before', even when I clicked my create button only once.

How can I solve this issue?

1
  • In your Observable use share() to avoid subscribing twice. Commented Feb 21, 2016 at 13:50

1 Answer 1

2

You need to be careful when using several async pipe on the same observable since this means that there are now several subscribers on it (the subscribe method is called several times, one per use of the async pipe).

In the case of an observable created from an HTTP call, the corresponding request will be called twice if subscribed twice)... By default such observables are cold (they can't be shared).

You need to make your observable hot using the share method:

this.status_async = this.status_async.share();
Sign up to request clarification or add additional context in comments.

8 Comments

I'm returning from http.post.map() and then in the view { status_async | async}. I noticed this.status_async = this.status_async.share(); doesn't work then anymore afterwards.
You set the return of the map method into the status_async property? Did you add the share operator like the map one?
Simply do the following: http.post(...).map(...).share(). This should work.
To import the share operator: import 'rxjs/add/operator/share';
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.