Modify the code to use a BehaviorSubject subscribing to an Observable

Currently, I am in the process of learning Angular2 and RxJS by studying someone else's application. The application consists of two modules:

asObservable.ts

export function asObservable(subject: Subject) {
    return new Observable(fn => subject.subscribe(fn));
}

The second module involves creating a new BehaviorSubject object in a file called todo-store.service.ts, which then sends it to the asObservable.ts module.

todo-store.service.ts

import {asObservable} from "./asObservable";
import {List} from "immutable";
import {Todo} from "./todo";
// Customized class for Todo

@Injectable()
export class TodoStore {

    private _todos: BehaviorSubject<List<Todo>> = new BehaviorSubject(List([]));

    get todos() {
        return asObservable(this._todos);
    }

    loadInitialData() {
        this.todoBackendService.getAllTodos()
            .subscribe(
                res => {
                    let todos = (<Object[]>res.json()).map((todo: any) =>
                        new Todo({id:todo.id, description:todo.description, completed: todo.completed}));
                    this._todos.next(List(todos));
                },
                err => console.log("Error retrieving Todos")
            )
    }
    // Unnecessary code has been omitted
 }

I am aiming to simplify my code by removing the asObservable.ts file and consolidating the subscribe function into a single function. However, my attempt at achieving this with the following snippet:

get todos() {
    return new Observable(Subject.subscribe(this._todos));
}

Is not successful. I would greatly appreciate some guidance on how to properly execute this task and an explanation of what mistakes I may be making. Thank you!

Answer №1

It appears the original writer may not have been aware of the existing asObservable() method. Personally, I find their approach requiring a Subject unnecessarily complex and lacking the ability to unsubscribe easily.

Personally, I would recommend sticking with the original asObservable() method. This way, you can hide the underlying use of a Subject and simply expose an Observable:

export class DataStore {
    // ...
    observable: Observable;

    constructor() {
        this.observable = this._data.asObservable();
    }
}

Subscribing is then straightforward:

let dataStore = // ... DataStore instance
dataStore.observable.subscribe(data => console.log(data));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Include a class in ul > li elements upon page load in Angular4

I attempted to add a class to each "li" element in an Angular4 page, but the class was not applied. Here is the relevant HTML code: <ul class="pagination"> <button class="previous" (click)="previous()">Previous</button> <button ...

I have an Observable but I need to convert it into a String

Seeking assistance with Angular translation service and Kendo.UI components. In the Kendo.UI documentation, it mentions the use of MessageService for component translation implementation. To achieve this, an abstract class must be extended containing a m ...

Guide on inserting a date into a MySQL DATETIME column in Angular with Node.js

In my application, I have a date picker component. My goal is to store the selected date in a MySQL database column with the data type of DATETIME. When using Angular, the value retrieved from the date picker is displayed as such: console.log(date.value): ...

How to disable the first option in an Angular 2 select dropdown

I'm working with a select component, and here is the code snippet I have: <select name="typeSelection" materialize="material_select" [(ngModel)]="trainingplan.type" > <option [ngValue] = "null" disabled selected>Please choose a ...

Ensure that the MUI icon color is set accurately

I created a functional component to set default values for react-admin's BooleanField. Here is the code: import ClearIcon from '@mui/icons-material/Clear' import DoneIcon from '@mui/icons-material/Done' import get from ...

Error in TypeScript while running the command "tsd install jquery" - the identifier "document" could not be found

Currently, I am facing an issue with importing jQuery into my TypeScript project. In order to achieve this, I executed the command tsd install jquery --save, which generated a jquery.d.ts file and added /// <reference path="jquery/jquery.d.ts" /> to ...

Tips for transferring data from a service to a method within a component

I have a service that successfully shares data between 2 components. However, I now need to trigger a method in component A when an event occurs on the service (and pass a value to that component). Can someone guide me on how to achieve this? I have seen ...

Tips for resolving the issue of dropdown menus not closing when clicking outside of them

I am currently working on an angular 5 project where the homepage consists of several components. One of the components, navbarComponent, includes a dropdown list feature. I want this dropdown list to automatically close when clicked outside of it. Here i ...

Greetings, Angular2 application with TypeScript that showcases the beauty of the world

I've been working on my first angular2 program and noticed some deviations from the expected output. typings.json: { "ambientDependencies": { "es6-shim": "github:DefinitelyTyped/DefinitelyTyped/es6-shim/es6-shim.d.ts#7de6c3dd94feaeb21f20054b9f ...

One cannot use a type alias as the parameter type for an index signature. It is recommended to use `[key: string]:` instead

I encountered this issue in my Angular application with the following code snippet: getLocalStreams: () => { [key: Stream['key']]: Stream; }; During compilation, I received the error message: An index signature parameter typ ...

Creating TypeScript utility scripts within an npm package: A Step-by-Step Guide

Details I'm currently working on a project using TypeScript and React. As part of my development process, I want to automate certain tasks like creating new components by generating folders and files automatically. To achieve this, I plan to create u ...

What is the best way to incorporate multiple pages and export them in an angular2 project?

Having some issues with my code. Can anyone lend a hand? import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: `page1.html` }) @Component({ selector: 'my-app2', templateUrl: `page2.html` ...

Ways to utilize a field from an interface as a type of index

interface Mapping { "alpha": (a: string) => void "beta": (b: number) => void } interface In<T extends keyof Mapping> { readonly type: T, method: Mapping[T] } const inHandlers: In<"alpha"> = { type ...

I continue to encounter the same error while attempting to deliver data to this form

Encountering an error that says: TypeError: Cannot read properties of null (reading 'persist') useEffect(() => { if (edit) { console.log(item) setValues(item!); } document.body.style.overflow = showModal ? "hidden ...

I am experiencing issues with the customsort function when trying to sort a column of

Seeking assistance with customizing the sorting function for a Date column in a primeng table. Currently, the column is displaying data formatted as 'hh:mm a' and not sorting correctly (e.g. sorting as 1am, 1pm, 10am, 10pm instead of in chronolog ...

What causes the HTML element's X position value to double when its X position is updated after the drag release event in Angular's CDK drag-drop feature?

I am facing a challenge with an HTML element that has dual roles: Automatically moving to the positive x-level whenever an Obsarbalve emits a new value. Moving manually to both positive and negative x-levels by dragging and dropping it. The manual drag a ...

Exploring TypeScript and React: Redefining Type Definitions for Libraries

As I transition from JSX to TSX, a challenge has arisen: My use of a third-party library (React-Filepond) This library has multiple prop types The provided types for this library were created by an individual not affiliated with the original library (@ty ...

Alert: Angular has detected that the entry point '@libray-package' includes deep imports into 'module/file'

Recently updated the project to Angular 9.1 and now encountering multiple warnings from the CLI regarding various libraries, such as these: Warning: The entry point '@azure/msal-angular' includes deep imports into 'node_modules/msal/lib-com ...

Tips for enabling the TypeScript compiler to locate bokeh's "*.d.ts" files

I recently made the switch from Bokeh's convenient inline extension framework to their npm based out of line build system. I'm currently working on getting my extension to build, but I've noticed that Bokeh organizes all TypeScript *.ts.d fi ...

Discover the best way to emphasize a chosen mat-list-item using color in Angular

Is there a way in Angular to highlight mat-list-item elements with red color when clicking on Notification, Dashboard, or Comments? <mat-list> <mat-list-item style="cursor: pointer" routerLink="/base/dashboard">Dashboard</mat-list-item ...