Tips for Ensuring the Observable Completes Before Subscribing

I utilized RXJS operators in my code to retrieve an array of locations.

Here is the code snippet:

return O$ = this.db.list(`UserPlaces/${this.authData.auth.auth.currentUser.uid}`, {
    query: {
      orderByChild: 'deleted',
      equalTo: false
    }
  })
  .map((locations: any) => {
    return locations.map(location => {
      return location.$key;
    });
  }).switchMap(ids => {
    return ids.map(id => {
      return this.db.object(`Devices/${id}`)
    });
  })
  .flatMap((x: any) => {
    return x;
  })
  .map((x:any)=>{
     if(!x.deleted){
      return x;
    }
  })
  .scan((acc:any, item) => [...acc, item],[])
  .do(console.log)

The array generated by the code is populated sequentially like so:

[{}] --> [{},{}] --> [{},{},{}] --> [{},{},{},{},...]

My goal is to obtain the complete array directly:

[{},{},{},{},...]

I attempted to use forkJoin but it did not resolve the issue:

return Observable.forJoin(O$) //but doesn't work.

If anyone has a solution to this problem, your help would be greatly appreciated. Thank you.

Answer №1

To harness the full potential of the subscription, use the subscribe method and patiently await either the triggering of the complete callback or an error being thrown:

const o$ = (...) // your ultimate observable
let array = null;
o$.subscribe({
    next: value => array = value,
    complete: () => {
        // The operation carried out by the observable has finished. No more values
        // will be produced. 'array' now holds the ultimate values generated
    },
    error: (error) => {
        // An error occurred. No further values will be produced
    }
});

Answer №2

Replace .scan with reduce()

.filter((x:any)=> {
 if(!x.deleted){
  return x;
 }
})
  .reduce((acc:any, item) => {
     acc.push(item)
     return acc
 },[])

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

What is the method for assigning a string to module variable definitions?

As someone new to TypeScript and MVC, I find myself unsure if I am even asking the right questions. I have multiple TypeScript files with identical functionality that are used across various search screens. My goal is to consolidate these into a single fil ...

Holding off on completing a task until the outcomes of two parallel API requests are received

Upon page load, I have two asynchronous API calls that need to be completed before I can calculate the percentage change of their returned values. To ensure both APIs have been called successfully and the total variables are populated, I am currently using ...

Create a new visual masterpiece using Canvas by repurposing an

I am currently working on the following code snippet; export default async function draw(elRef : RefObject<HTMLCanvasElement>, tileData : TileProps) { const canvas = elRef.current!; const ctx = canvas.getContext('2d')!; ctx.clearRect( ...

Tips for handling undefined values in observable next methods to return a default error message

I sent a request over the network and received a response. Whenever I encounter an undefined value in the response, I want to return a default error message. The response may contain multiple levels of nested objects. Is there a way to replace the if else ...

storing information in localStorage using react-big-calendar

Incorporating react-big-calendar into my project, I encountered a problem where the events in the calendar would disappear upon page refresh despite saving them in localStorage. I had planned to store the events using localStorage and retrieve them later, ...

Error: 'process' is not defined in this TypeScript environment

Encountering a typescript error while setting up a new project with express+ typescript - unable to find the name 'process'https://i.stack.imgur.com/gyIq0.png package.json "dependencies": { "express": "^4.16.4", "nodemon": "^1.18.7", ...

Typescript Code Coverage with karma-jasmine and istanbul: A complete guide

I am attempting to calculate the Code Coverage for my typescript Code in karma framework using Istanbul. In the karma.conf file, typescript files are added and through karma typescript-preprocessor we are able to conduct unit testing and code coverage of t ...

Angular project service file experiencing issues with TypeScript string interpolation functionality

Here is the code snippet for a service in an Angular project: @Injectable() export class FetchDataService { fetch(link){ console.log('This is a ${link}'); } } In my component, I am invoking this method with a string parameter. Upon che ...

Using type values in TypeScript

I am trying to assign interfaces as values within a config object: export interface RouterConfig { startEvents?: typeof RouterEvent[]; completeEvents?: typeof RouterEvent[]; } The intended usage is as follows: private config: RouterConfig = { star ...

Should Angular libraries be developed using Typescript or transpiled into JavaScript?

Currently, I am in the process of developing a library that will be available as an Angular module through npm. The library itself has been written using typescript. Everything was functioning perfectly up until Angular version 5.0.0, but after this update ...

Utilize a string to access and sort the properties of a class in TypeScript

Let's discuss a simple problem involving objects in Javascript. Take for example an object like this: var obj={ par1:'value1', par2:'value2' } In JavaScript, we can access the values like obj['par1']. Now, the q ...

Angular device redirection allows you to automatically redirect users based on the device

Currently in my Angular project, I am attempting to dynamically redirect users based on their device type. For example, if the user is on a Web platform, they will be redirected to www.web.com. If they are on an Android device, they should go to www.androi ...

Processing HTTP requests routed from Firebase Hosting to Cloud Functions

I'm currently working on integrating data patching with my Firestore database using http. My goal is to achieve this without relying on an external server, by utilizing Firebase Hosting and Functions. Firstly, I set up my Firebase project and importe ...

Assembly of these elements

When dealing with a structure where each property is of type These<E, A> where E and A are unique for each property. declare const someStruct: { a1: TH.These<E1, A1>; a2: TH.These<E2, A2>; a3: TH.These<E3, A3>; } I inte ...

Is there a way to selectively filter and display certain data in an Angular data table?

I am currently working on a project using Angular 7 frameworks that involves dealing with large amounts of data. One of the tasks is to filter out trial units based on the 'userName' field in the raw data. I have various usernames such as user22 ...

Utilizing a library that solely enhances the functionality of the Array object

I have a library with type definitions structured like this: declare global { interface Array<T> { addRange<T>(elements: T[]): void; aggregate<U>(accumulator: (accum: U, value?: T, index?: number, list?: T[]) => an ...

What steps are required to transform a TypeScript class with decorators into a proper Vue component?

When I inquire about the inner workings of vue-class-component, it seems that my question is often deemed too broad. Despite examining the source code, I still struggle to grasp its functionality and feel the need to simplify my understanding. Consider th ...

Determining the type inference in Typescript based on column data objects

Within my object that describes my table, I have a property called dataFields, which is an array of data with 3 keys - name (a required string), label (a required string), and field (an optional string). Now, I would like to add another property called tes ...

Obtain the name of a node using its identification number in D3JS

I am currently working on implementing a generalized tooltip feature. This tooltip will display the name and other relevant data of the active node. For example, if node 3 is currently active, the tooltip will show the name and distance (not link distance) ...

Modify the color of the matSnackbar

I'm having trouble changing the snackbar color in Angular using Angular Material. I tried using panelClass in the ts file and adding it to the global css, but the color remains unchanged. Any suggestions on how to resolve this? I am still new to this ...