I implemented a simple BehaviorSubject,

import {BehaviorSubject} from"rxjs";class MyWeirdoClass { constructor() {} private st: Subject= new BehaviorSubject(null); changeSt(val:boolean){ this.st.next(val); } val(){ this .st.subscribe(res=>{ if (res){ console.log(res); } }) } stStatus() { this.val(); this.changeSt(true); this.val(); this. changeSt(false); this.val(); }}

Running stStatus() now displays the following output on the console.

truetrue

Although I expect the value

falsetruefalse

What's wrong with my implementation?

Solution:

The output you get is correct:

this.val();

This only makes the first subscription unable to print anything because of if(res){...} .

this.changeSt(true);

Set the value to true to be printed by the first subscription.

this.val();

Make the second subscription print the second true.

this.changeSt(false);

You set it to false, which is ignored by all subscribers due to if(res){...} .

this.val();

Same as above.

javascript - BehaviorSubject with boolean value not working as expected Related posts

  1. how to put JavaScript into JavaScript?

    I tried (but it doesn't work):Here is the tutorial I use for this purpose:Solution:Try this:When encountering issues like this, it's a good idea to check your browser for javascript errors. Different browsers display it differently, but look for a javascript console or something like that. Also, che ...

  2. javascript garbage collection [Revisit JavaScript basics (3)]

    Foreword:JavaScript has an automatic garbage collection mechanism. The principle of this garbage collection mechanism is actually very simple: find out those variables that are no longer used, and then release the memory occupied by them. To this end, the garbage collector will periodically perform this operation at a fixed time interval (or the scheduled collection time during code execution).generallyNow let's analyze the normal life cycle of local variables in the function. Local variables on ...

  3. Use JavaScript to dynamically load JavaScript

    After over an hour trying to get it to work, I think it's because of the cross-domain policy, but I really think this will work. I can't find much info about it either. However, here's my problem. I have a name For the website of http://mysite.com, then I include the third party script (what I'm wri ...

  4. More JavaScript preloaders for JavaScript

    I have seen some tutorials on how to create a JavaScript preloader for images. Is it possible to use the JavaScript preloader for other JavaScript?My website uses mootools (and others) for animations and lots of pictures etc.-so it takes a while to load. Is it possible that the website has a"load"in ...

  5. JavaScript (JS) Javascript Object (2)

    https://www.cnblogs.com/haiyan123/p/7594046.htmlIn JavaScript, data types other than null and undefined are defined as objects, and variables can also be defined by creating objects. String, Math, Array, Date, and RegExp are all important built-in objects in JavaScript. In JavaScript programs Most f ...

  6. application/javascript and text/javascript

    I am reading the HTML 5 Canvas animation tutorial using javascript (of course). In the title, the author used application/javascript which is very new to me because I have only seen used text/javascript. Can anyone help ? This question has probably been asked before, but I am using the phone to oper ...

  7. Use Javascript to load other external Javascripts

    I have a JS code library that can be loaded from a folder. Instead of typing <script src='...'></script> to arrange line by line in the tags of the HTML document, is there a way to link a Javascript file, This file can organize and automatically load other javascript files.I know that Do ...

  8. [javascript] Javascript notes

    1. At 12:28:16 on October 20, 2019, learn HOW2J Javascript,2. The commonly seen abbreviation js means javascript;3. The javascript code must be placed in the script tag, the script tag can be placed anywhere in the html, it is generally recommended to be placed in the head tag.4. What is a piece of ...

  9. [timeisprecious][JavaScript ]JavaScript RegExp \W Metacharacter

    JavaScript>RegExp regular expression> \W metacharacter1. From RunnobJavaScript RegExp \W metacharacterDefinition and usage:The \W metacharacter is used to find non-word characters.Word characters include: az, AZ, 0-9, and underscore.grammar:new RegExp("\W") or a simpler way: /\W/Demo:Case Code ...

  10. [JavaScript] JavaScript Interview Question 1

    JavaScript interview questions 1Scope:Topic 1: var v = 123; function foo() { var v = 456; function inner() { console.log(v) } return inner } result = foo(); console.log(result()) result: var v = 123; function foo() { var v = 456; function inner() { console.log(v) } return inner } result = foo(); //4 ...

  11. JavaScript learning: JavaScript array iteration method

    The array iteration method operates on each array item. 1. The forEach() method calls a function (callback function) for each array element. ForEach loops through each item of the array. This method has no return value. A callback function, the callback function has three parameters, the first is th ...

  12. Understanding Javascript's async

    forewordThis article is 2925 words, and it takes about 10 minutes to read.Summary: This article sorts out the difference between asynchronous code and synchronous code execution, Javascript's event loop, task queue, micro-task queue and other concepts.Original address: Understanding Asynchronous Jav ...

  13. 5 JSON&JavaScript conversion&JavaScript:void(0)&JavaScript code specification

    JSON: JavaScript Object Notation JS Object NotationA lightweight data exchange format used to store and transmit data, usually used by the server to transfer data to web pagesIs an independent language, easy to understandJSON syntax rules:The data is a key/value pair, and a name corresponds to a value.Data separated by commaCurly braces hold objects, square brackets hold array key-value pairsExample: JSON syntax defines the employees object{"employees":[ {"firstName":"John", "lastName":"Doe"}, ...

  14. JavaScript study notes-1. Understand JavaScript

    Baidu Encyclopedia:  JavaScript is a scripting language belonging to the network, which has been widely used in Web application development. It is often used to add various dynamic functions to web pages and provide users with smoother and beautiful browsing effects. Usually JavaScript scr ...

  15. inline javascript, what is 'javascript' in 'javascript: alert('asdf')" repeat]?

    See answer in English > What does the JavaScript pseudo protocol actually do? 2 I don't write inline javascript, but I see and use it all the time in the codebase I use:<div onClick='javascript:alert("asdf");'></div>I did some testing and found that in all my browsers, even if IE is i ...

  16. JavaScript Docs and other JavaScript layout engines?

    Is there a JavaScript layout engine for laying out text in Google documents? I know that Google Docs will do some crazy things to get the job done (to avoid things like designMode and contentEditable completely, Microsoft Office Online does similar things).Solution:None of these are what you want, a ...

Recent Posts

  1. python-Find word co-occurrence

    So here is my problem. I have a very large csv file with 3 columns. The first column is a unique ID. The second column is a string of English sentences. The third column is a string of word tags for Describe the sentences in the second column (usually 3 tags, up to 5). This is an example.id | senten...

  2. javascript-prevent the menu key from displaying the context menu

    I know that the keyboard menu key is keyCode === 93.So I have the following code:$(window).on("keydown", document, function(event){ if (event.keyCode === 93) {//context menu console.log("context menu key", event); event.preventDefault( ); event.stopPropagation(); return false; }});Although the event...

  3. java – Where is the Stringbuilder object created?

    Strings are immutable because they are stored in the constant string pool. So, where is the stringbuilder object created? Say, I created two string builder objectsStringBuilder s1 = new StringBuilder("abc"); StringBuilder s2 = new StringBuilder("abc");I will end up with two separate objects in the h...

  4. Use jQuery/Ajax in PHP to display current progress

    Short and sweet: looking for a way to call the PHP file and use jQuery and/or Ajax to display the progress. Call the PHP file upgrade.php? step = 1, then append the returned output to #upgradestatus. After completion, upgrade.php will be called? step = 2 and append the output until the specified num...

  5. java Share a SmartUpload Chinese garbled fixed jar package

    Don’t know how to upload files, leave a message or QQ1596913818...

  6. python – Tensorflow One Hot Encoder?

    Is tensorflow similar to the one hot encoder of scikit learn, used to process classified data? Will placeholders using tf.string behave as categorical data?I realize that I can manually preprocess the data before sending it to tensorflow, but the built-in data is very convenient.Solution:Starting fr...

  7. from English to English?

    This question has been answered here:> Using streams, how can I map the values in a HashMap? 3 said I have a Map<String,Integer>. Is there an easy way to get Map<String,String> from?In short, I don't mean this:Map mapped = new HashMap<>();for(String key: originalMap.keySet()) {m...

  8. JNDI path of java-JDBC data source?

    I sometimes see JDBC data sources specified in JNDI that use the"jdbc"path. For example, the following (for Tomcat6):But sometimes I see"jdbc"in the JNDI pathname. Is using"jdbc"just a convention? Is it typical? Where are these things recorded?Solution:This is just a convention. You can call the res...

  9. javascript-how to remember to use cookies to show and hide div

    I have HTML like:content is visibleButton Expand +I use Jquery to show/hide the div, such as:$(document).ready(function () {$("#expand-hidden").click(function () {$("#mainleft-content").toggle(); });});I want to use cookies to remember that the state of the div is to hide or show the visitor's manip...

  10. java-parse NullPointerException caused by logInInBackground

    I have a similar login method:private void login() { String username = this.email.getText().toString(); String password = this.password.getText().toString(); ParseUser.logInInBackground(username, password, new LogInCallback() { @Override public void done(ParseUser user, ParseException e) { if (user ...