Encountering a syntax issue with pipeable operators in Angular Rxjs

I am currently in the process of rewriting this code snippet:

Observable
    .merge(this.searchQuery$, this.lazyQuery$)
    .do(() => this.loadingPage())
    .map(filter => this.buildURL("jaume", Config.security['appName'], filter))
    .switchMap(url =>
        this.service.getItemsFromStorage(url)
        .map(response => this.buildPage(response))
        .catch(() => Observable.of(pojo.Page.EMPTY))
    )
    .do(page => this.loadedPage(page))
    .takeUntil(this.unsubscribe$)
    .subscribe();

My goal is to utilize "pipable" syntax. So far, I have been able to rewrite it as follows:

this.searchQuery$.pipe(
    merge(this.lazyQuery$),
    tap(() => this.loadingPage()),
    map(filter => this.buildURL("jaume", Config.security['appName'], filter))
)
.pipe(
    switchMap(url => this.service.getItemsFromStorage(url)),
    catchError(() => Observable.of(pojo.Page.EMPTY))
)
.pipe(
    tap(page => this.loadedPage(page))  <<***>>
);

However, I am encountering a compiler error on <<***>>:

Argument of type 'Response | Page' is not assignable to parameter of type 'Page'. Type 'Response' is missing the following properties from type 'Page': total, users

It appears that the catchError is returning a {} | Page type when it should be returning a single Page type.

Any insights on how to resolve this issue?

Answer №1

You forgot to link a response to a page.

merge(this.searchQuery$, this.lazyQuery$).pipe(
  tap(() => this.loadingPage()),
  map(filter => this.buildURL("jaume", Config.security['appName'], filter)),
  switchMap(url => this.service.getItemsFromStorage(url).pipe(
    map(response => this.buildPage(response)), // <-- don't forget this map in your code
    catchError(() => of(pojo.Page.EMPTY))
  )),
  tap(page => this.loadedPage(page)),
  takeUntil(this.unsubscribe$)
).subscribe();

Don't forget to refer to the official migration guide for more information: Howto: Convert to pipe syntax

Answer №2

Firstly, there is an excessive amount of pipes being used unnecessarily. Consider simplifying. Additionally, you can utilize of() instead of Observable.of() for a shorter and clearer code.

this.searchQuery$.pipe(
    merge(this.lazyQuery$),
    tap(() => this.loadingPage()),
    map(filter => this.buildURL("jaume", Config.security['appName'], filter)),
    switchMap(url => this.service.getItemsFromStorage(url)),
    catchError(() => of(pojo.Page.EMPTY)),
    tap(page => this.loadedPage(page))  <<***>>
);

This approach should work effectively.

The error lies in TypeScript's interpretation of the return value, not in the functionality itself. Specify the return type explicitly, like so:

...
catchError(() => of(<Page>pojo.Page.EMPTY))
...

If the issue pertains to the catchError section.

Update #1 - Nesting

If you only need to apply a specific pipe at a particular point in the chain, insert the pipe where the observable is returned. For instance:

...
switchMap(() => of(null).pipe(
  catchError(...)
))

Instead of chaining multiple .pipe() methods like:

.pipe(...),
.pipe(...),
.pipe(...),

You can consolidate them into one:

.pipe(
...
...
...
)

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

Creating a React component with a column allowing multiple checkbox selections in NextUI table

Setting up multiple "checkbox" columns in a table using the NextUI table has been my current challenge. Each row should have selectable checkboxes, and I want these selections to be remembered when navigating between pages, running searches, or removing co ...

Tips for optimizing file sizes in an Angular 11 app for production deployment

Currently, I am troubleshooting an issue with my application where some of my production files are taking a long time to load. I have already deployed my application and tried using the --aot and optimizer commands during the production build process. Here ...

Navigating the use of property annotations in Mapped Types with remapped keys

After exploring the concept of Key Remapping in TypeScript, as shown in this guide, I am wondering if there is a way to automatically inherit property annotations from the original Type? type Prefix<Type, str extends string> = { [Property in keyo ...

Guide to reference points, current one is constantly nonexistent

As I work on hosting multiple dynamic pages, each with its own function to call at a specific time, I encounter an issue where the current ref is always null. This poses a challenge when trying to access the reference for each page. export default class Qu ...

What could be causing FormArrayName to consistently display as undefined in my HTML code, even when the safe-navigation operator is employed

Currently, I'm referring to the Angular Material example found at https://angular.io/api/forms/FormArrayName Upon initializing the packageForm formGroup in ngOnInit() and logging it in the console during ngAfterViewInit(), I can see that the translat ...

What is the best way to calculate checksum and convert it to a 64-bit value using Javascript for handling extremely large files to avoid RAM overflow?

Question: What is the best method for generating a unique and consistent checksum across all browsers? Additionally, how can a SHA256/MD5 checksum string be converted to 64-bit? How can files be read without requiring excessive amounts of RAM when ...

Incorporating Kekule.js into a TypeScript-based React application

Greetings, community! I've created a React app designed to help individuals in the field of chemistry share their work. To facilitate this, I came across a library called Kekule.js Here is the link Utilizing TypeScript poses a challenge as it requir ...

Tips for filtering data using an array within an object containing arrays

Below is the provided information: userRoom = ['rm1']; data = [{ name: 'building 1', building: [{ room: 'rm1', name: 'Room 1' },{ room: 'rm2', name: ' ...

"Utilizing Typescript and React to set a property's value based on another prop: A step-by

Is there a way to create a dynamic prop type in React? I have an Alert component with various actions, such as clicking on different components like Button or Link. I am looking for a solution like this: <Alert actions={[{ component: Link, props: { /* ...

Programmatically initiate form submission in Angular with dynamic status and classes

Presented in a sequential manner, I have various questions within a form that can be navigated forwards and backwards by the user. To make this process smoother, I have incorporated the functionality to use the left and right arrow keys with the help of on ...

Tips for accessing and manipulating an array that is defined within a Pinia store

I have set up a store to utilize the User resource, which includes an array of roles. My goal is to search for a specific role within this array. I've attempted to use Array functions, but they are not compatible with PropType<T[]>. import route ...

Leveraging Angular 2 directives in TypeScript to bind a value from a custom control to an HTML control

I have created a unique custom directive named "my-text-box", and within this directive, I am utilizing the HTML control <input>. I want to pass values from my custom control to the HTML input control. In Angular 1, I would simply do something like & ...

Encountering an error of ExpressionChangedAfterItHasBeenCheckedError while trying to refresh the

I'm encountering an issue that I need help with: https://i.stack.imgur.com/4M54x.png whenever I attempt to update the view using *ngIf to toggle on an icon display. This is what my .ts file looks like: @Component({ selector: 'app-orders&ap ...

What is the process for importing types from the `material-ui` library?

I am currently developing a react application using material-ui with typescript. I'm on the lookout for all the type definitions for the material component. Despite attempting to install @types/material-ui, I haven't had much success. Take a look ...

Troubleshooting the ReferenceError: Blob is not defined problem with the heic2any library in a Next.js application

Currently, I am encountering an issue where everything is properly implemented and functioning smoothly. However, the main problem arises when I attempt to reload the page, as it results in an error message: ReferenceError: Blob is not defined. This issue ...

Invoking a Typescript function from the Highcharts load event

Struggling to call the TypeScript function openDialog() from the events.load of Highcharts? Despite using arrow functions, you are running into issues. Take a look at the code snippet below: events: { load: () => { var chart : any = this; ...

Is there a way to dynamically define the return type of a function in Typescript?

Can the variable baz be dynamically assigned the string type? type sampleType = () => ReturnType<sampleType>; // Want to return the type of any function I pass (Eg. ReturnType<typeof foo>) interface ISampleInterface { baz: sampleType; } ...

TypeScript - ESBuild - Encountered an unexpected '<' token

When compiling TypeScript files for a React app with esbuild, everything goes smoothly. However, upon checking the browser console, an error pops up: An unexpected token '<' is causing errors after the return statement // components/editor/ ...

Restrict the properties of an object to match the properties of a different object

I am currently developing an Object patching utility function with the following code snippet class Test{ a:number; b:number; } var c:Test={a:0,b:1} function patchable<T>(obj:T){ return { patch:function<K>(prop:K){ return patc ...

Mysterious issue arises during deployment of Typescript-React application on Heroku

I am working on a TypeScript-React application generated using create-react-app. Deploying it to Heroku is proving to be a challenge as the process fails with an error message during installation and build: remote: Creating an optimized production b ...