Questions tagged [observable]

An observable is a commonly used programming component that can be "monitored" by other elements of the code, referred to as the "observers". Various frameworks and programming languages offer diverse approaches when it comes to observables, thus it is advisable to use this tag in combination with others.

What is the method for generating an observable that includes a time delay?

Question In order to conduct testing, I am developing Observable objects that simulate the observable typically returned by an actual http call using Http. This is how my observable is set up: dummyObservable = Observable.create(obs => { obs.next([ ...

What is the process for extracting components from a JSON file using an observable in Angular?

Take a look at this snippet of code: response: any; fetchData(url: any) { this.response = this.http.get(url); } ngOnInit(): void { fetchData("url.com/data.json"); console.log(this.response) } When I check the console, I see Obser ...

Different types of subscriptions for forkJoin observable

I am currently making two API requests with typed responses and combining them using the Observable.forkJoin method. My goal is to store each of the results in separate typed variables. var observableOrganization: Observable<Organization> = this.get ...

Angular 2 failing to recognize service variable changes initiated from component

Hello there, I'm currently facing a challenge with updating my component to reflect the correct value of a service variable whenever it changes. Here's what I have so far: Snippet from Component1 HTML {{icons | json}} Component1 Code icons: ...

What is the recommended way to use the async pipe to consume a single Observable property in a view from an Angular2

Suppose I have a component with the following property: import { Component, OnInit } from 'angular2/core'; import { CarService } from 'someservice'; @Component({ selector: 'car-detail', templateUrl: './app/cars/ ...

Angular 6 Time Discrepancy

I am trying to display real-time time difference on the UI that updates every second. Here is what I have attempted: component.ts import { Component, OnInit } from '@angular/core'; import 'rxjs/add/observable/of'; import 'rxjs/add/observable/interval'; ...

Tips on transforming Angular 2/4 Reactive Forms custom validation Promise code into Observable design?

After a delay of 1500ms, this snippet for custom validation in reactive forms adds emailIsTaken: true to the errors object of the emailAddress formControl when the user inputs [email protected]. https://i.stack.imgur.com/4oZ6w.png takenEmailAddress( ...

Using Angular: filtering data streams from a date range observable object

I have a piece of code that seems to be functioning correctly, but I can't shake the feeling that it might just be working by chance due to an undocumented feature. I'm torn between questioning its validity or accepting that it is indeed designed ...

From a series of arrays filled with objects, transform into a single array of objects

Upon using my zip operator, I am receiving the following output: [ [Obj1, Obj2, ...], [Obj1, Obj2, ...] ]. To achieve my desired result, I am currently utilizing the code snippet below: map(x => [...x[0], ...x[1]]) I am curious to know if there exists ...

Creating a stream of observables in RxJs and subscribing to only the latest one after a delay: A comprehensive guide

I am trying to create a stream of Observables with delay and only subscribe to the last one after a specified time. I have three HostListeners in which I want to use to achieve this. I would like to avoid using Observable form event and instead rely on H ...

Angular 5 with Typescript encountered a failure in webpack due to the absence of the property "data" on the Response

I am encountering an issue during webpack compilation. It compiles successfully if I remove .data, but then the page crashes with calls from template->component (which in turn calls a service). Here is the error I am facing: ERROR in src/app/components ...

Can you explain the distinction between Observable<ObservedValueOf<Type>> versus Observable<Type> in TypeScript?

While working on an Angular 2+ project in Typescript, I've noticed that my IDE is warning me about the return type of a function being either Observable<ObservedValueOf<Type>> or Observable<Type>. I tried looking up information about Obs ...

Merging an unspecified number of observables in Rxjs

My latest project involves creating a custom loader for @ngx-translate. The loader is designed to fetch multiple JSON translation files from a specific directory based on the chosen language. Currently, I am implementing file loading through an index.json ...

You can't access the values from one subscribe in Angular 2 within another subscribe (observable) block

Is there a way to properly handle the values from the subscribe method? I am facing an issue where I want to use this.internships in another subscribe method but it keeps returning undefined. Your assistance is greatly appreciated! Code: ngOnInit(): voi ...

How to implement angular 2 ngIf with observables?

My service is simple - it fetches either a 200 or 401 status code from the api/authenticate URL. auth.service.ts @Injectable() export class AuthService { constructor(private http: Http) { } authenticateUser(): Observable<any> { ...

Guide to Displaying Individual Observable Information in HTML with Ionic 3

When using Observable to retrieve a single object from Firebase, how can I display this data on an HTML page? I attempted to use {{(postObservable2|async)?.subject}}, but it does not render. Another approach involved AngularFireObject, yet it resulted in ...

Angular: Implementing conditional HTTP requests within a loop

Currently, I am facing a challenge where I need to loop through an array of objects, check a specific property of each object, and if it meets certain criteria, make an HTTP request to fetch additional data for that object. The code snippet below represen ...

Is it time to end my MediaObserver subscription in flex-layout for Angular?

Within my Angular component, I have implemented the following code to display different elements based on screen resolution: constructor(private mediaObserver: MediaObserver) {} private mySubscription: Subscription; public ngOnInit(): void { this.my ...

Ways to utilize the scan operator for tallying emitted values from a null observable

I'm looking for an observable that will emit a count of how many times void values are emitted. const subject = new Subject<void>(); subject.pipe( scan((acc, curr) => acc + 1, 0) ).subscribe(count => console.log(count)); subject.next ...

Angular 2's Observable does not directly translate to a model

While delving into Angular 2, I experimented with utilizing an observable to retrieve data from an API. Here's an example of how I did it: getPosts() { return this.http.get(this._postsUrl) .map(res => <Post[]>res.json()) ...

Make sure to wait for the observable to provide a value before proceeding with any operations involving the variable

Issue with handling observables: someObservable$.subscribe(response => this.ref = response); if (this.ref) { // do something with this.ref value } ERROR: this.ref is undefined How can I ensure that the code relying on this.ref only runs after ...

What is the best way to refine the dataSource for a table (mat-table) using ngx-daterangepicker-material?

I am facing a new challenge and feeling unsure about how to approach it. The issue at hand is filtering a table based on the date range obtained through the ngx-daterangepicker-material library. This library triggers events that provide a start date and a ...

The Observable pipeline is typically void until it undergoes a series of refreshing actions

The issue with the observable$ | async; else loading; let x condition usually leads to staying in the loading state, and it requires multiple refreshes in the browser for the data to become visible. Below is the code snippet that I utilized: // TypeScript ...

Leveraging the power of socket.io in conjunction with redux-observable for enhanced functionality (react, rxjs,

Looking for a solid demonstration on integrating redux-observable with socket.io. Any examples out there? I'm aiming to structure my application in a way that specific actions are channeled through the socket, and information from the socket (already ...

Exploring the Power of Observables in Angular 2: Chaining and

Hi there! I'm relatively new to Angular and still getting the hang of observables. While I'm pretty comfortable with promises, I'd like to dive deeper into using observables. Let me give you a quick rundown of what I've been working on ...

Displaying sorted objects from Angular serviceIn Angular 8, let's retrieve an object

In my Angular8 application, I am running a query that fetches a data object. My goal is to sort this data object based on the order value and then display each product item on the browser. For example, here is an example of how the output should look like ...

Sign up for a feature that provides an observable exclusively within an if statement

There is an if clause in my code that checks for the presence of the cordova object in the window global object. If cordova is present, it will make a http request and return the default angular 2 http observable. If the application is in a web context wh ...

What benefits does Observable provide compared to a standard Array?

In my experience with Angular, I have utilized Observables in the state layer to manage and distribute app data across different components. I believed that by using observables, the data would automatically update in the template whenever it changed, elim ...

The Angular service uses httpClient to fetch CSV data and then passes the data to the component in JSON format

I'm currently working on an Angular project where I am building a service to fetch CSV data from an API server and convert it to JSON before passing it to the component. Although the JSON data is successfully logged in the console by the service, the comp ...

Enhancing the functionality of Angular 2's ngModel directive with the utilization of observables

Working with Angular 2's ngModel directive involves variables and functions, such as: <input [ngModel]="myVar" (ngModelChange)="myFunc($event)" /> I am interested in using BehaviorSubjects instead of variables and functions: < ...

How to effectively manage errors in TypeScript using RxJS?

Exploring subscribe arguments in the official RxJS documentation has raised some interesting questions for me. For instance, what is the purpose of using error: (e: string) => { ... } to catch errors emitted by an observable? Despite this implementation ...

Creating your own custom operator using observables is a powerful way

const apiData = ajax('/api/data').pipe(map((res: any) => { if (!res.response) { console.log('Error occurred.'); throw new Error('Value expected!'); } return res.response; }), An enhancement is needed to encapsulate the pipe function in a custom ope ...

Working with multiple observables in an array of properties using RXJS

I'm relatively new to using rxjs in my angular projects and I'm facing a challenge with a simple scenario. When making an http call to retrieve a group, it returns data including a list of "buddy ids", "genre ids", and a "region id". In order to get the ...

Retrieving information from an http request within a for loop in an Angular 2+ application

I have a scenario where I need to call my http request inside a for loop in order to process 1000 items at a time. Here's the code snippet that implements this logic: getData(IDs: string[]): Observable<any> { // IDs is a large array of strings, a ...

I'm looking to find the Angular version of "event.target.value" - can you help me out?

https://stackblitz.com/edit/angular-ivy-s2ujmr?file=src/app/pages/home/home.component.html I am currently working on getting the dropdown menu to function properly for filtering the flags displayed below it. My initial thought was to replicate the search ...

Why is it advantageous to use Observable as the type for Angular 5 component variables?

Being a beginner in Angular 6, I have been exploring the process of http mentioned in this link: https://angular.io/tutorial/toh-pt6#create-herosearchcomponent One thing that caught my attention was that the heroes array type is set to Observable in the ...

Explore the Ability to Monitor Modifications to an Object's Property in Angular2/Typescript

Can we track changes to an object's field in Angular2/Typescript? For instance, if we have a class Person with fields firstName, lastName, and fullName, is it feasible to automatically modify fullName whenever either firstName or lastName is altered? ...

When utilizing Rx.Observable with the pausable feature, the subscribe function is not executed

Note: In my current project, I am utilizing TypeScript along with RxJS version 2.5.3. My objective is to track idle click times on a screen for a duration of 5 seconds. var noClickStream = Rx.Observable.fromEvent<MouseEvent>($window.document, &apos ...

Change Observable<String[]> into Observable<DataType[]>

I'm currently working with an API that provides me with an Array<string> of IDs when given an original ID (one to many relationship). My goal is to make individual HTTP requests for each of these IDs in order to retrieve the associated data from the ...

Using Angular BehaviorSubject in different routed components always results in null values when accessing with .getValue or .subscribe

I am facing an issue in my Angular application where the JSON object saved in the service is not being retrieved properly. When I navigate to another page, the BehaviorSubject .getValue() always returns empty. I have tried using .subscribe but without succ ...

Using Observables in Angular 2 to send polling requests

I have the following AngularJS 2 code snippet for polling using GET requests: makeHtpGetRequest(){ let url ="http://bento/supervisor/info"; return Observable.interval(2000) .map(res => res.json()) //Error here ...

Having Trouble with Angular 6 Subject Subscription

I have created an HTTP interceptor in Angular that emits a 'string' when a request starts and ends: @Injectable({ providedIn: 'root' }) export class LoadingIndicatorService implements HttpInterceptor { private loadingIndicatorSour ...

What is the best way to output data to the console from an observable subscription?

I was working with a simple function that is part of a service and returns an observable containing an object: private someData; getDataStream(): Observable<any> { return Observable.of(this.someData); } I decided to subscribe to this funct ...

Ways to pass data to a different module component by utilizing BehaviourSubject

In multiple projects, I have used a particular approach to pass data from one component to another. However, in my current project, I am facing an issue with passing data from a parent component (in AppModule) to a sidebar component (in CoreModule) upon dr ...

Is it possible that overwriting my observable variable will terminate existing subscribers?

I am looking for a way to cache an http call and also trigger the cache refresh. My UserService is structured like this: @Injectable() export class UserService { private currentUser$: Observable<User>; constructor(private http: HttpClient) { } ...

"Regardless of the circumstances, the ionic/angular service.subscribe event

Currently, while developing the login section of my Ionic app, I am encountering an issue with the getTokenAsObservable.subscribe() function. The main problem is that the function checks the token status when it is saved (by clicking the Login button) or ...

Looping Through RxJS to Generate Observables

I am facing the challenge of creating Observables in a loop and waiting for all of them to be finished. for (let slaveslot of this.fromBusDeletedSlaveslots) { this.patchSlave({ Id: slaveslot.Id, ...

Error with Angular 2 observables in TypeScript

When a user types a search string into an input field, I want to implement a debounce feature that waits for at least 300 milliseconds before making a request to the _heroService using HTTP. Only modified search values should be sent to the service (distin ...

What is the best way to transform the data stored in Observable<any> into a string using typescript?

Hey there, I'm just starting out with Angular and TypeScript. I want to get the value of an Observable as a string. How can this be achieved? The BmxComponent file export class BmxComponent { asyncString = this.httpService.getDataBmx(); currentSt ...

Issue with clearing subscription upon navigating to another page is not functioning as expected

Currently, I am working on building a basic search screen to gain a better understanding of Angular subscriptions, which I have found to be quite perplexing. On my home page, I have set up two components - one for filtering and the other for displaying sea ...

What are the most effective applications for utilizing an Observable Data Service?

Within my application setup, I have integrated a data service at the core level. The majority of functions within my app involve actions taken on the data model, to which components react. My goal is for components to be able to subscribe to the data ser ...

Angular application triggering multiple subscribe method calls upon a link click event

Here is the code for my navbar component: <li *ngFor="let item of menu"> <a *ngSwitchCase="'link'" routerLinkActive="active" [routerLink]="item.routerLink" (click)="Navigation(item.title)"> ...

The process of subscribing to a service in Angular

I currently have 3 objects: - The initial component - A connection service - The secondary component When the initial component is folded/expanded, it should trigger the expansion/folding of the secondary component through the service. Within the service ...

Managing business logic in an observable callback in Angular with TypeScript - what's the best approach?

Attempting to fetch data and perform a task upon success using an Angular HttpClient call has led me to the following scenario: return this.http.post('api/my-route', model).subscribe( data => ( this.data = data; ret ...

Using Angular to display asynchronous data with ngIf and observables

In cases where the data is not ready, I prefer to display a loader without sending multiple requests. To achieve this, I utilize the as operator for request reuse. <div class="loading-overlay" *ngIf="this.indicatorService.loadingIndicators[this?.indic ...

Utilize an Angular HttpInterceptor to invoke a Promise

I have an angular HttpInterceptor and I am in need of invoking an encryption method that is defined as follows: private async encrypt(obj: any): Promise<string> { However, I am unsure of how to handle this within the HttpInterceptor: intercept(req ...

Assign a value to ReplaySubject if it is currently devoid of any

I am facing a challenge with my ReplaySubject in the component after content initialization. Whenever it initializes, it always gets set to "/api/bulletin/getall" value and overrides any value assigned to it before in the onViewChanged function. How can ...

Tips for retrieving a string instead of an Observable in @angular/http

I'm currently integrating Angular 4 with .NET Core Web API. The Web API is providing a CustomerName as a string based on the Id given. Here is the service method in Angular 4. I know that angular/http needs to return an Observable due to it being an asyn ...

Guide to iterating through an Observable<Object[]> to generate an array of objects

Google Firestore collection named users is structured as follows : { "contactNumber":"0123456789", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="88e2e7e0e6ece7edc8efe5e9e1e4a6ebe ...

Ways to provide information to an rxjs observer

It appears that most people find observers to be a piece of cake, but I personally struggle with them. I am trying to set up an observable that can receive a number input after it has been created, triggered by pressing a button. However, all the examples ...

RxJS Transformation is failing to return the updated object

In my Angular 5.1 single page application, I am encountering an issue with a service response while calling REST services. The problem lies in how the response is handled when it returns an array of Events. Here is how I am trying to transform the response ...

"Exploring the process of unsubscribing or disposing of an interval observable based on a certain condition in Angular2 or

I am embarking on the journey into Rx and reactive programming, facing a situation that requires me to continuously monitor a hardware's status by sending a POST request to its REST API every 500ms. The goal is to stop the interval observable once the re ...

What is the method for gathering an array of emitted values from Observable.from?

So I'm working with Rxjs and have a bunch of code: return Observable.from(input_array) .concatMap((item)=>{ //This section emits an Observable.of<string> for each item in the input array }) .sc ...

Even after the component is destroyed, the subscription to the service observable continues to emit

I'm facing an issue with an observable in my service. The provided code below demonstrates this: @Injectable({ providedIn: 'root' }) export class MyService { public globalVariable: BehaviorSubject<string> = new BehaviorSubject(''); } A feature ...

Exploring the sharing of observables/subjects in Angular 2

UPDATE: After further investigation, it appears that the SharedService is being initialized twice. It seems like I may be working with separate instances, causing the .subscribe() method to only apply to the initiator. I'm not sure how to resolve this issu ...

What steps should I follow to ensure that the processData function waits for the data returned by the getData function in Angular?

After calling the getData function, each object is stored in an array and returned. Now I need the processData function to await these results from getData and then further process them. However, when I try to console.log(cleaningData), I don't see any r ...

Using TypeScript to chain observables in a service and then subscribing to them in the component at the end

Working with Platform - Angualar 2 + TypeScript + angularFire2 Within my user.service.ts file, I have implemented the following code to initiate an initial request to a firebase endpoint in order to fetch some path information. Subsequently, I aim to util ...

Determine the presence or absence of data in an Angular Observable

Here is an example of how I am making an API call: public getAllLocations(): Observable<any> { location = https://v/locations.pipe(timeout(180000)); return location; } In my appl ...

Angular HTTP Requests with Observables

In order to enhance the security of my Angular web application, I am currently in the process of developing a TypeScript method that will validate a JWT token on the server using an HTTP call. It is imperative for me that this method returns a boolean val ...

Angular loop using an HTTP GET request is producing garbled information

Currently, I have a loop that includes an http GET request. This is the sample loop code: for (let index = 0; index < datas.length; index++) { let car = datas[index].smiles; console.log('or--> ' + car); this.subscr = this.CarService.getCar ...

Exploring Angular 2's Observable Patterns and Subscribing Techniques

Despite perusing various posts and documentation on the topic, I am still unable to grasp the concept of observables and subscribing to them. My struggle lies in updating an array in one component and displaying it in another component that is not direct ...

Exploring the method of subscribing to streams in Angular2

I have a streaming web-service running on localhost:8080/stream that responds whenever a new message is added to the subscribed mqtt stream. I am looking to integrate this web-service into my Angular2 app using RxJS to consume NodeJS APIs. The code snipp ...

In Angular 6, when using Put and Post methods with HttpParams, the return type can be modified to Observable<HttpEvent<T>>

I encountered a situation where I am performing a POST request and receiving a JSON object in response. When I use only the URL and body parameters in the POST request, the return type is Observable<T>. However, when I include additional parameters ...

Fullcalendar in Angular fails to update events automatically

I am exploring the integration of fullcalendar with angular. Despite adding valid events to my events field, they are not displaying in the UI. However, hardcoded events are appearing. I am relatively new to angular, so the issue may not be directly relat ...

Angular: Merge two Observables to create a single list and fetch the combined data

I am currently working on creating a function that returns an observable with a list, compiled from several observables. I feel like I am very close to finding the solution because the debugger stops right before displaying the list. Here is my code: ts t ...