I'm puzzled by how my observable seems to be activating on its own without

Sorry if this is a silly question.

I am looking at the following code snippet:

  ngOnInit(): void {


    let data$ = new Observable((observer: Observer<string>) => {
      observer.next('message 1');
    });
      
    data$.subscribe(s => console.log(s));
  }

I can see that 'message 1' is being displayed in the console output. I am confused about when and how observer.next is being called.

I have declared the variable data$ which holds an Observable object. But I am not sure why the observer.next method is being triggered automatically.

Answer №1

When you subscribe to your observable, the observer function is triggered. This can be seen when multiple subscriptions are made with varying results, as shown below:

import {Observable} from 'rxjs';

const source$ = new Observable(observer => observer.next(Math.random()));

source$.subscribe(console.log); // Displays a random number
source$.subscribe(console.log); // Shows a different random number each time

This phenomenon is known as a cold observable. For more information on the differences between hot and cold observables, check out this informative article. You can also view the example on Stackblitz.

Answer №2

Your Observable operates in this way

let stream$ = new Observable((observer: Observer<string>) => { observer.next('message 1') });

Is a powerful tool, but to activate it you must use .subscribe(...)

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

Intellisense fails to function properly after attempting to import a custom npm package

I've encountered an issue with a custom npm package that I created using storybook. The components function properly in other projects when imported, but the intellisense feature is not working as expected. Interestingly, when I import the same compon ...

The typescript error TS2339 is triggered by the property 'webkitURL' not being found on the 'Window' type

Currently utilizing Angular 2 in a project that is compiled with TypeScript. Encountering an issue when attempting to generate a blob image: Error TS2339: Property 'webkitURL' does not exist on type 'Window' The TypeScript code causi ...

Dealing with Errors in Node.js Using Typescript and Express

As I embark on my journey with Node and Typescript, a question has cropped up in my mind. There are two key files in my project: server.ts import express = require('express'); import IConfiguration from "../config/config"; export default clas ...

Loading dynamic content within Angular Material tabs allows for a more customized and interactive user experience

I am currently working on creating a dynamic tab system using Angular Material: Tabs. I have encountered an issue with loading content on tabs after the initial one, where the functionality only works when the first tab is loaded. Below you can see the ta ...

Enhancing the session object with new properties

I am attempting to include extra properties in the session object req.session.confirmationCode = confirmationCode; However, I encounter an error stating that the property confirmationCode does not exist Property 'confirmationCode' does not exist ...

Error TS2315: Invalid Type Assignment for Angular 6 ModuleWithProviders

Hey there, I'm encountering an issue that's got me scratching my head. I've shared some of my code in the hopes that it might shed some light on the problem. The problem cropped up as soon as I started working on a Reactive Form. Let me s ...

Passing parent HTML attributes to child components in Angular 2

Is there a way to pass HTML attributes directly from parent to child without creating variables in the parent's .ts class first? In the sample code below, I am trying to pass the "type=number" attribute from the parent to the app-field-label component ...

The 'data' property is absent in the 'never[]' type, whereas it is necessary in the type of product data

Hello, I am new to TypeScript and I'm struggling with fixing this error message: Property 'data' is missing in type 'never[]' but required in type '{ data: { products: []; }; }'. Here is my code snippet: let medias :[] ...

Assign a value to a variable within an asynchronous function

Initially, I understand that initializing variables inside asynchronous functions is not a feasible approach. However, I require assistance in rectifying this issue. In the following example, I have an observable and aim to extract its variable for use i ...

The 'type' property is not present in the 'ChartComponent' type, however, it is necessary in the 'ApexChart' type

Encountered an error highlighted in the title: Property 'type' is missing in type 'ChartComponent' but required in type 'ApexChart'. Any attempt to resolve this issue led to another error message: Type '{ type: string; ...

Can someone please explain how to display a specific element from a JSON Array?

Is there a way to display only this specific part? /db/User_DataDb/61500546-4e63-42fd-9d54-b92d0f7b9be1 from the entirety of this Object obj.sel_an: [ { "__zone_symbol__state":true, "__zone_symbol__value":"/db/User_DataDb/61500546-4 ...

Leveraging the import statement within lib.d.ts to enhance Intellisense functionality in Visual Studio Code

Looking to streamline my JavaScript project by utilizing custom global variables and harnessing the power of VSCode intellisense for auto completion. Here's what I'm aiming for: See example of auto completion for 'lol' After some sear ...

Angular Universal does not fully render on the server side

Currently, my project involves integrating Angular 4 with Angular Universal and Knockout. The main objective is to have the Angular application generate HTML on the server side for SEO purposes. As part of this process, I need to utilize KnockoutJs to bin ...

Transforming the color of the navbar upon a scrolling action is implemented through Angular's [ngClass

New to Angular and looking to implement a feature where the navbar changes from transparent to dark upon scrolling. However, my current implementation keeps the navbar transparent even after scrolling. Any tips on achieving this functionality? Here is the ...

Error: The argument provided cannot be assigned to a parameter that requires a string type, as it is currently a number

Currently, I am in the process of migrating some older websites to TypeScript. However, I keep encountering a type error during the build process. The specific error message is Type error: Argument of type 'number' is not assignable to parameter ...

Exploring ways to cycle through a select dropdown in React by utilizing properties sent from the Parent Component

I'm having trouble displaying the props from a parent component in a modal, specifically in a select dropdown. How can I make it so that the dropdown dynamically shows the values from the props instead of the hardcoded 'Agent' value? What am ...

Ways to turn off specific ngtsc warnings

Ever since updating my Angular app to version 15, I've been noticing some warnings popping up in both the terminal and Chrome DevTools. Is there a way to turn off or disable these warnings? I keep seeing this warning message about the optional chain o ...

Leverage the key-value pairs in JSON to automatically suggest types within the function parameters

If we have data structured like this: { "key1": "hardcoded string", "key2": "another hardcoded string", } Imagine a function with 2 parameters where the first parameter should refer to key1 and the second to i ...

Encountering issues importing 'angulars/router' into Plunker environment

I'm encountering an issue with Plnkr when trying to import the router class in my project import {Component} from '@angular/core' import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from '@angular/router'; An error messag ...

Retrieve Json data from an external API in Angular by utilizing the HttpClient module

Being a novice in angular, I am experimenting with fetching data from an external API. Although I managed to retrieve the data successfully on the console, I encountered errors when attempting to display it on the screen. Below are the details of my setup: ...