Why is my RxJS timer not waiting for the specified time?

I'm diving into the world of RxJS and trying to grasp its concepts. During some testing, I encountered a puzzling issue that has me stumped.

Below is the snippet in question :

let item = { id: 1, name: 'chair' };

const asyncItem = timer(2000).pipe(() => of(item));

asyncItem.subscribe(data=>console.log(data))

I anticipated seeing item displayed in the console after a 2-second delay, but strangely it appears instantly. Where am I going wrong? Grateful for any insights. Thanks.

Answer №1

If you want to trigger an emission after a certain number of seconds, make sure to utilize the delay operators instead of using timer.

To achieve this, modify your code as follows:

const asyncProduct = of(product).delay(2000)

asyncProduct.subscribe(data => console.log(data))

UPDATE: You can also opt for the timer operator within a pipe, combined with another operator like shown below:

timer(2000).pipe(
switchMap(() => of(product))
).subscribe(data => console.log(data))

By following this approach, the value will be emitted after 2 seconds, helping you accomplish your desired outcome. This presents an alternative method compared to the initial example provided earlier.

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

Exploring the location of unit testing within async-await in Angular applications

I have been working with Angular 9+ along with karma test runner and jasmine test framework for my unit tests. My focus is on unit testing only the app component which includes dependency injection: app.component.ts import { Component, EmbeddedViewRef } ...

Ensuring Function Parameter Usage in Typescript and Angular 5

Currently, I am developing a component using Angular 5 and Ionic 4. My objective is to include a Refresher event to hide the refresh spinner whenever the user triggers the final function to conceal the spinner. Provided below is an excerpt of my code: e ...

Using constant variables as arguments in functions in TypeScript

While learning about TypeScript, I encountered some confusion regarding how it handles const variables. Let's consider a scenario where I define an interface for a number: interface MyNumber { value: number; } If I then create a constant MyNumbe ...

Tips for invoking a service from another in angular version 6

The following code snippet showcases Service 1, specifically the uploadAttachment method which executes an http post call. This method is invoked from Service 2. However, in Service 2, the instance of Service 1 is consistently undefined, resulting in a fai ...

Utilizing ElementRef to create collapsible elements in Angular

Implementing basic collapse in Angular using ElementRef has proven to be a challenge for me, especially when dealing with HTML content within an ngFor loop. I need to pass the index value to the click event so it can retrieve the ID of the element. Check ...

Alerts appear immediately upon beginning to type, asking for 8 characters and ensuring both passwords match

Is it possible to notify users that both passwords should match and they need to enter at least 8 characters after typing? There is currently an issue where a notification appears for entering less than 8 characters, but the password reset still proceeds ...

Error: Loki cannot be used as a constructor

Can anyone assist me in understanding why this code is not functioning correctly? Here's what my index.ts file in Hapi.js looks like: import { Server, Request, ResponseToolkit } from '@hapi/hapi'; import * as Loki from 'lokijs'; ...

Can you explain the meaning of `((prevState: null) => null) | null`?

Upon encountering this code snippet: import { useState } from "preact/hooks"; export default function Test() { const [state, setState] = useState(null); setState('string'); } An error is thrown: Argument of type 'string' ...

How to eliminate all special characters from a text in Angular

Suppose I receive a string containing special characters that needs to be transformed using filter/pipe, with the additional requirement of capitalizing the first letter of each word. For instance, transforming "@!₪ test stri&!ng₪" into "Test Stri ...

Is there a way in NodeJS to preview the contents of a file in a browser before initiating the download process?

Is there a way to preview a file in the browser before downloading it in NodeJS? This would allow users to make sure they are choosing the correct file to download. Currently, I have this code for downloading a file: app.get("/download/file", (req, res) = ...

Ways to utilize a single node_modules folder across multiple projects

Is there a simple method to centralize and share one node_modules folder among all Angular projects, thereby preventing the need to download the same dependencies each time we start a new project? If so, is this approach recommended (what are the pros and ...

Encountering an error with "unexpected token import" while utilizing localize-router in an Angular 4

I am currently working on building an Angular 4 app with server-side rendering and language-specific route paths. I am using Angular CLI version 1.5.0-rc1 for this project. While everything seems to be functioning fine, I am facing a problem with incorpor ...

Guide to utilizing Angular's translate i18n key as a dynamic parameter within HTML

Looking to pass an i18n translate service key as a parameter function on an HTML component. Attempted the following, but instead of getting the text, it's returning the key value. Created a variable assigned with the title in the component.ts file. ...

Attempt to re-establish connection to server callback in Angular 2 upon encountering failure

tag, I have created an API parent class where all the necessary methods are implemented for server communication. The ApiService class is injected with Http and MdSnackBar services to handle HTTP requests and display snack bar messages. The get() method ...

Hold off until the operation finishes executing and then deliver Angular 6

Is there a way to delay the subscribe function until my logic is complete and the transform method has updated the keys object? transform(value: any, args:string) : any { let keys = []; this.http.get('src/app/enum-data/enum.json').subsc ...

"Tips for removing all child elements from a parent element using Angular's Renderer2 in versions 5 and above

Manipulating the DOM programmatically is recommended using Angular's Renderer2. Within my directive, I extract some text from el.nativeElement.innerText, modify it, and aim to append it to my element: const text = renderer.createText(`${el.innerTex ...

What strategies should be employed to develop an Angular 4 application seamlessly integrated with Asp.NET Core?

I attempted to test out a couple of templates which turned out to be unsuccessful: https://github.com/asadsahi/AspNetCoreSpa https://github.com/MarkPieszak/aspnetcore-angular2-universal Unfortunately, neither of them worked properly for me. I'm cu ...

Incorporating Firebase administrator into an Angular 4 project

Currently encountering an issue while trying to integrate firebase-admin into my angular project. Despite my efforts, I am unable to resolve the error that keeps popping up (refer to the screenshot below). https://i.stack.imgur.com/kdCoo.png I attempted ...

Angular: Changing the class of a parent element dynamically while iterating through a list with ngFor

I have a unique challenge where I am trying to style a checkbox as a button by placing it inside its label. <label> <input type="checkbox" name="..."> </label> My goal is to toggle the parent label's class based on whether the che ...

The custom validator in Material2 Datepicker successfully returns a date object instead of a string

Im currently working on developing a unique custom validator for the datepicker feature within a reactive form group. Within my code file, specifically the .ts file: form: FormGroup; constructor( private fb: FormBuilder, ...