Comparing Angular2: The benefits of subscribing to Observables versus using singleton

Summary:

Link to example

What is the benefit of using a service's local variable instead of subscribing to an observable within the service?

Illustrative Example:

In the provided plunker, there are two components and a service. Both components share an Observable stored in the service.

In the service, I update a public variable and emit that value to the subscribers.

This piece of code appears redundant to me, but it is commonly used in Angular 2 tutorials.

src/number.ts

this.num = {
  num: new Date().getTime()
};

this.observer.next(this.num);

What are the advantages of each approach? Personally, I lean towards the subscription method, but they appear to achieve the same result. What am I overlooking?

NOTE: The setInterval and NgZone code is only for demonstration purposes. In a real application, this data would be fetched through HTTP requests, updating the variable and sending the data to the subscribers. Since we are just fetching time every second, NgZone had to be utilized as well.

Answer №1

When dealing with Observables, the main issue is usually around receiving values only when events are emitted. However, sometimes you need immediate access to the latest value and then be notified of any future updates.

A helpful solution is using a BehaviorSubject, which immediately provides new subscribers with the last emitted value. For those less familiar with Rx, an alternative approach mentioned in your question can also be used:

this.prop = this.service.num; this.service.observable.subscribe(value => this.prop = value);

This method ensures that you get the most recent value right away and receive updates as they happen through the observable.

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

Saving JSON data retrieved from the server into an array in Angular 2

Using a nodejs server to retrieve data from an SQL database has been challenging. I attempted to store the data in taches, which is an array of Tache : getTaches(): Observable<Tache[]> { return this.http.get(this.tachesUrl) .map(response => ...

The formatting directive fails to keep pace with speedy input

I am working on a feature to automatically format the input field as the user types, transforming the letters into valid initials in uppercase with dots in between. The formatting needs to happen in real-time as the user inputs characters, rather than aft ...

The required dependencies for google-chart-angular are not found

I have been trying to set up google-chart-angular in my Angular project by following the steps outlined in this tutorial. I have also added GoogleChartsModule to my app.module.ts file. Although I believe everything is set up correctly, when I try to run t ...

Execute the React Native application on Windows by using the command npx react-native run-windows

I recently created a test application using React Native by running npx react-native init Test --template react-native-template-typescript (https://reactnative.dev/docs/typescript). Everything seemed to be working fine, but I encountered an issue where the ...

Exploring Data in Angular 2: Examining Individual Records

I am currently learning Angular and facing some challenges in structuring my questions regarding what I want to achieve, but here is my query. Within a component, I am retrieving a single user record from a service. My goal is to display this user's ...

Developing components and injecting them dynamically in Angular 2 using Typescript remotely

I am currently exploring the potential of Angular 2 as a foundational technology for a flexible administration dashboard, emphasizing the need for extensibility and customization. I envision an environment where external developers can create their own c ...

Traveling from one child route to another

I am encountering issues with route navigation between child routes, as I keep receiving "routes not found" errors. Despite trying multiple solutions like injecting and refreshing after child configuration, I still face difficulties in navigating to a spec ...

Getting the version from package.json in Next.js can be easily achieved by accessing the `version

In my quest to retrieve the "version" from the package.json in a Next.js application, I encountered a roadblock. I attempted using process.env.npm_package_version, similar to how it is done in a Node application, but unfortunately, it returned undefined. ...

Difficulty reloading after updating input using AngularJS ngTable

I'm encountering an issue where I need to utilize ngTable with TableParams to load and modify a table. For instance, when the page initializes, entering a number in the textbox for the first time displays the appropriate number of rows in the table. ...

Styling Issues with Angular Code within App-Root Element

I am encountering an issue with my Angular 7 application during initialization. I have a class named "testing" that simply changes the text color to red. I tried placing the class in the index.html file within a style tag, as well as in the styles.scss fil ...

Failure on the expect statement when comparing numbers in Jest..."The Jest magic number comparison is

I am currently conducting a test to verify that the magic number of a Buffer is in zip format. This involves extracting the first 4 bytes of the buffer into a string and comparing it with the magic number for zip, which is PK. const zipMagicNumber: str ...

NestJS encountered an error while running the test suite: module 'src/article/article.entity' could not be located from 'comment/comment.entity.ts'

I am facing an issue with NestJS and Jest testing. As a newcomer to NestJS, I encountered the "Cannot find module" error when running tests. Specifically, the error message I received while trying to test my service was: src/article/article.service.spec. ...

Display the autocomplete dropdown in Angular 2+ only once the user has typed at least one letter

Looking to create a customized autocomplete feature using Angular 2+ and angular material design, where the options are only displayed after at least one letter has been typed. The default behavior of the autocomplete is to toggle on focus even when the i ...

What is the best way to determine which option is most suitable: types, classes, or function types in TypeScript for

Currently, I am developing a small todo command line utility with a straightforward program structure. The main file is responsible for parsing the command line arguments and executing actions such as adding or deleting tasks based on the input provided. E ...

Maintain query parameters in Angular6 while routing with canActivate

When using Auth guard to verify login status and redirecting to the login page if a user is not logged in, there seems to be an issue with losing all query parameters during the redirection process. I attempted to preserve the query params by adding { qu ...

Triggering createEffect in SolidJS with an external dependency: A guide

Is there a way to use an external dependency to trigger the createEffect function in Solid, similar to React's useEffect dependency array? I am trying to execute setShowMenu when there is a change in location.pathname. const location = useLocation() ...

Saving data from rowclicked event in ag-grid with Angular

My goal is to save the event data from the onRowClicked event in a Component member. This way, when the user clicks a button, the data can be deleted. However, I am facing an issue where the member variable becomes undefined when trying to access it in t ...

Provide a parameter for a function's callback

I am attempting to utilize lodash's debounce function to delay the onChange event. See the code snippet below. import React, { useState, useEffect, useCallback } from "react"; import { TopBar } from "@shopify/polaris"; import { debounce } from "lodas ...

Flow error: Unable to access the value of this.props.width as the property width is not defined in T

In my React Native project, I am utilizing Flow for type checking. For more information, visit: I currently have two files named SvgRenderer.js and Cartoon.js where: Cartoon extends SvgRenderer Below is the source code for both of these files: SvgRend ...

Creating a singular and distinctive string by combining two keywords

Is it possible to create a single distinct string by combining two keywords regardless of the order in which they are entered? EDIT: The keywords in question are numerical rather than alphabetical characters. The following example is merely for explanator ...