How to use RXJs Subject like store variable in Svelte? You can use the Subject variable in Svelte with $ prefix. But when you bind the variable to input it throws an exception: "Error: name.set is not a function" because the Subject type has not a set method.
Asked
Active
Viewed 364 times
1 Answers
2
You can use RxJs Subject like a store variable in Svelte as in the example below.
<script>
import {Subject} from "rxjs";
let name = new Subject();
setTimeout(()=>{name.next("text")}, 1000);
</script>
<h1>Hello {$name}!</h1>
But if you try to use the name
variable with a bind
directive it throws an exception: "Error: name.set is not a function".
<script>
import {Subject} from "rxjs";
let name = new Subject();
$: console.log($name);
</script>
<h1>Hello {$name}!</h1>
<input bind:value={$name} />
To solve this issue, you can add a set method to the Subject class with a simple trick :).
<script>
import {Subject} from "rxjs";
Subject.prototype.set = function (value) {
this.next(value);
}
let name = new Subject();
$name = "Ali";
$: console.log($name);
</script>
<h1>Hello {$name}!</h1>
<input bind:value={$name} />

cacheoff
- 251
- 3
- 5
-
Example code in [Svelte REPL](https://svelte.dev/repl/2780007481384d678fbdf5089cb041a1?version=3.38.2) – cacheoff May 23 '21 at 17:29