Develop a directive for transforming data

In my latest project, I am looking to develop a LoaderDirective that can fetch an observable, display a spinner while loading the data, and then switch to showing the actual data once loaded. I also want it to expose the loaded data using the 'as' keyword.

My desired usage for this directive would be:

<div *load="items$ as items">

Here is what I have managed to achieve so far:

@Directive({
  // tslint:disable-next-line:directive-selector
  selector: '[load]',
})
export class LoadDirective<T> {
  private data: T;

  @Input()
  set load(observable: Observable<T>) {
    observable.subscribe({
      next: value => this.loaded(value),
      error: error => this.showError(error)
    });
  }

  constructor(
    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef,
    private componentFactoryResolver: ComponentFactoryResolver
  ) {
    this.viewContainer.clear();
    this.viewContainer.createComponent(this.componentFactoryResolver.resolveComponentFactory(SpinnerComponent));
  }

  private loaded(value: T) {
    this.data = value;
    this.viewContainer.clear();
    this.viewContainer.createEmbeddedView(this.templateRef, {load: this.data});
  }

  private showError(e: string) {
    this.viewContainer.clear();
    const errorComponent = this.viewContainer.createComponent(this.componentFactoryResolver.resolveComponentFactory(ErrorComponent));
    errorComponent.instance.error = e;
  }
}

The challenge I'm facing is that the input data is expected to be an observable, thus necessitating the output to also be of type Observable. Is there a different method to handle this scenario similar to how we use TransformPipe in pipes? How can I resolve this particular issue?

Answer №1

Check out my solution below to see if it meets your needs.

For an example, you can visit this link

I made a slight adjustment to your code as follows

Previously:

this.viewContainer.createEmbeddedView(this.templateRef, {load: this.data});

Changed to:

const viewRef = this.viewContainer.createEmbeddedView(this.templateRef);
viewRef.context.data = this.data;

Updated Template:

<div *appLoader="data$; data as result">
    {{result | json}}
</div>

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

Using Angular2 translate in expressions: a step-by-step guide

Looking at the code below, you'll notice that starting from line 44, the titles are already enclosed within {{}} expressions: import { Component, ViewChild } from '@angular/core'; import { Events, MenuController, Nav, Platform } from ' ...

Angular subscription and observable continuously fetch information

I'm encountering an issue with utilizing subscriptions and observables Here is my code This is my inventory.service.ts getInventoryList = (page: string, pageSize,size) => { const userLocation = this.authService.getUserLocation(); let que ...

Struggling to determine the necessary modules to import in order to successfully integrate Firestore with Angular services

Recently, I developed a simple service with the following structure: @Injectable({ providedIn: "root" }) export class ItemService { private db!: CollectionReference<DocumentData>; constructor(private firestore: Firestore) { this. ...

What is the process for translating the aria-label to "Open calendar" in a different language for the angular md-datepicker icon?

Check out my latest demo on using the angular md-datepicker Looking to customize or translate the aria-label text for the icon in the angular md-datepicker, as shown in the image below. ...

What is the best way to manage the 'content' attribute in TSX?

I'm currently developing an application that utilizes schema.org. In the code snippet below, you can see how I've implemented it: <span itemProp="priceCurrency" content="EUR">€</span> According to schema.org do ...

Error in AWS Cloud Development Kit: Cannot access properties of undefined while trying to read 'Parameters'

I am currently utilizing aws cdk 2.132.1 to implement a basic Lambda application. Within my project, there is one stack named AllStack.ts which acts as the parent stack for all other stacks (DynamoDB, SNS, SQS, StepFunction, etc.), here is an overview: im ...

Eliminate the need to input the complete URL every time when making server calls

Currently, my springbok application has a React-Typescript frontend that is functioning well. I am using the request-promise library to make requests like this: get('http://localhost:8080/api/items/allItems', {json: true}). However, I would like ...

The outcome of using Jest with seedrandom becomes uncertain if the source code undergoes changes, leading to test failures

Here is a small reproducible test case that I've put together: https://github.com/opyate/jest-seedrandom-testcase After experimenting with seedrandom, I noticed that it provides consistent randomness, which was validated by the test (running it multi ...

What is the method for adjusting the border color of an ng-select component to red?

I am having an issue with the select component in my Angular HTML template. It is currently displaying in grey color, but I would like it to have a red border instead. I have tried using custom CSS, but I haven't been able to achieve the desired resul ...

Develop a carousel component using Vue.js

I'm currently working on a dashboard that needs to display cards, but I'm running into an issue. I want only four cards visible at a time, and when you click the arrow, it should move just one step to the next card. For example, if cards 1-4 are ...

Service in Angular2 designed to retrieve JSON data and extract specific properties or nodes from the JSON object

Currently, I am trying to teach myself Angular2 and facing some difficulties along the way. I am working on creating a service that loads a static JSON file. Right now, I am using i18n files as they are structured in JSON format. The service will include a ...

Is it feasible to transmit telemetry through a Web API when utilizing ApplicationInsights-JS from a client with no internet connectivity?

My Angular application is running on clients without internet access. As a result, no telemetry is being sent to Azure. :( I am wondering if there is a way to configure ApplicationInsights-JS to call my .Net Core WebApi, which can then forward the inform ...

Developing a constrained variable limited to specific values

Recently delving into Typescript - I am interested in creating a variable type that is restricted to specific values. For instance, I have an element where I want to adjust the width based on a "zoom" variable. I would like to define a variable type call ...

Exploring TypeScript and React Hooks for managing state and handling events

What are the different types of React.js's state and events? In the code snippet provided, I am currently using type: any as a workaround, but it feels like a hack. How can I properly define the types for them? When defining my custom hooks: If I u ...

Dependencies in Angular 2 are essential for efficient functioning

Let's examine the dependencies listed in package.json: "dependencies": { "@angular/common": "2.2.1", "@angular/compiler": "2.2.1", "@angular/core": "2.2.1", "@angular/forms": "2. ...

The Angular client fails to receive data when the SignalR Core Hub method is called from the Controller

Issue with Angular SignalR Client not Receiving Data from ASP.NET API I have a setup where an angular website is connected to an asp.net back-end using SignalR for real-time data service. Everything was working fine when tested in localhost, but after pub ...

Seeking clarification on how the Typescript/Javascript and MobX code operates

The code provided below was utilized in order to generate an array consisting of object groups grouped by date. While I grasped the overall purpose of the code, I struggled with understanding its functionality. This particular code snippet is sourced from ...

Exported data in Vue3 components cannot be accessed inside the component itself

Essentially, I'm working on creating a dynamic array in Vue3. Each time a button is clicked, the length of the array should increase. Below is the code snippet. <div class="package-item" v-for="n in arraySize"></div> e ...

What is the best way to check the API response status in NextJS13?

Currently, I am experimenting with different methods to handle API HTTP status in my NextJS-13 project but so far nothing has been successful. Note: TypeScript is being used in this project. Below is my code snippet with a static 200 API response and the ...

Potential Issue: TypeScript appears to have a bug involving the typing of overridden methods called by inherited methods

I recently came across a puzzling situation: class A { public method1(x: string | string[]): string | string[] { return this.method2(x); } protected method2(x: string | string[]): string | string[] { return x; } } class B extends A { prot ...