The parameter type x cannot be assigned to the argument type '(x) => ObservableInput<{}>'

Looking for some insights on this issue

Currently working with ngrx and attempting to utilize multiple switchMaps to call various action classes.

Defined Actions:

export class BlogAddedAction implements Action {

    readonly type = BLOG_ADDED_ACTION;

    constructor(public payload:any) {

    }

}
export class CrudSucessAction implements Action {

    readonly type = CRUD_SUCCESS_ACTION;

    constructor(public payload:any) {

    }
}

export class BlogAddedToDBAction implements Action {

    readonly type = BLOG_ADDED_TO_DB_ACTION;

    constructor(public payload:any) {

    }
}

effects.ts:

  @Effect() addBlog$: Observable<any> = this.actions$
  .ofType<BlogAddedAction>(BLOG_ADDED_ACTION)
    .switchMap(action =>  {
        console.log(action)
    return this.blogService.addBlog(action.payload.blog)
    })
    .switchMap((action)=>new BlogAddedToDBAction(action))
    .map((action)=>new CrudSucessAction(action))
}

Encountering a TypeScript error:

[ts]
Argument of type '(action: Blog) => BlogAddedToDBAction' is not 
assignable to parameter of type '(value: Blog, index: number) => ObservableInput<{}>'.Type 'BlogAddedToDBAction' is not assignable to type 'ObservableInput<{}>'.
Type 'BlogAddedToDBAction' is not assignable to type 'ArrayLike<{}>'.Property 'length' is missing in type 'BlogAddedToDBAction'.

Attempted using map instead of a second switchMap but BlogAddedToDBAction is not being executed.

Answer №1

When deciding between using switchMap and mergeMap, it's important to consider the behavior you want. switchMap is ideal for emitting an Observable that can be canceled, like an addBlog HTTP request. However, if you need to add a blog before the previous one is finished, mergeMap may be a better choice to avoid canceling the request prematurely. More information on this topic can be found here.

It's important to note that switchMap requires an Observable-compatible value to be emitted, so returning a plain object like BlogAddedToDBAction won't work. Instead, consider using

of(new BlogAddedToDBAction(action))
to create an Observable that emits the object. However, this may not always be the desired outcome.

In your current setup, the Effect is only emitting the CrudSuccessAction, but you may want to emit both actions. In this case, using merge to combine the actions may be a better approach. Here's an example of how you could update your code:

@Effect() addBlog$: Observable<any> = this.actions$.pipe(
  ofType<BlogAddedAction>(BLOG_ADDED_ACTION),
  mergeMap(action =>  {
    console.log(action)
    return this.blogService.addBlog(action.payload.blog).pipe(
      mergeMap(action => [new BlogAddedToDBAction(action), new CrudSucessAction(action)]),
      catchError(() => of(new CrudErrorAction())
  });

By using mergeMap with an array, each value within the array will be emitted sequentially. You can test this behavior with a simple example:

of(1).pipe(mergeMap(() => [1, 2])).subscribe(console.log); // logs 1, then 2

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

Ways to develop a dynamic Promise-returning Function

I find myself in a situation where I am aware of the type of data that will be returned when making a request to an API. Here is the function I have: const fetchData = async (url: string, options?: Object): Promise<any> => { const res = await f ...

Problem with connecting Angular data

<body ng-app="myAPP"> <div ng-controller="employeeCtrl"> <table style="border:1px solid gray"> <tr> <th>Employee Name</th> <th>Employee Address</th> <th> ...

Ways to verify if MatDialog is shown using a mock during an angular unit test

A unique feature of my current project involves utilizing a component that, upon a button click, triggers a pop-up to greet the user. To achieve this functionality, I have implemented Angular Material Dialog for handling the pop-up display. The specific co ...

Tips for resolving conflicts between sequelize and angular within a lerna monorepo using typescript

Managing a monorepo with Lerna can be quite challenging, especially when working with both Node.js and Angular in the same project. In my setup, Angular is using "typescript": "~3.5.3". For Node.js to work seamlessly with Sequelize, I have the following ...

What could be causing routerLink to malfunction despite correct configuration?

Is routerLink properly placed in the view? <p><a routerLink="/registration" class="nav-link">Register</a></p> Checking my app.module import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular ...

A guide on the correct way to fork an Ionic Stencil Component

I am interested in customizing the columns and position of ion-datetime to use it in my Ionic app. However, I am unsure how to approach this without resorting to messy copy-and-paste solutions. Are there any better methods for achieving this customizatio ...

Encountering the ExpressionChangedAfterItHasBeenCheckedError message despite updating the property via the @Output event

Attempting to update a property on the parent component through an event in the child component has proved challenging. Research suggests that this can be achieved using @Output as it is the recommended method to transmit data from child component to pare ...

Tips for typing a narrow JSX.Element

Is there a way to create a variable in React that can be either a component or a string? Like this: function MyComponent(): JSX.Element { let icon: JSX.Element | string = "/example.png"; return <div>{typeof icon === "JSX.Element" ? icon : <i ...

Initializing a component in Angular 2 using third party callbacks

My ultimate objective is to create a custom Google Maps component using Angular2. The Google Maps API comes with its own library that can be initialized using a <script> tag either with or without a callback function. An example of initializing it ...

Could the "IonApp" class found in @ionic/angular (Ionic 4) be considered the updated version of the "App" class in ionic-angular (Ionic 3)?

I am currently in the process of upgrading an older Ionic app to Ionic 4. Previously, there were no issues before the migration I am working on a provider file helper.ts, and I have encountered a problem during the migration. Here is the output of ionic ...

Can the CDK be used to reboot both RDS and EC2 instances simultaneously?

After diving into using CDK, I am a newcomer to programming. I have successfully set up a basic environment including an EC2 instance, a VPC with 2 subnets, and an RDS instance. Additionally, I've configured CloudWatch Alarms to monitor the CPU usage ...

Set the class function to be uninitialized

I'm a little unsure of my TypeScript knowledge. I have a class MyClass with a member variable that is a function, but I don't know what this function will be at compile time. I want to allow external code to set this function dynamically during r ...

When you call Subscribe(), you will receive the output "complete: () => void; 'complete' is defined in this context. What exactly does this signify?

Currently, I am following a tutorial and after meticulously checking and rechecking, I can confidently say that my code matches exactly with the one the professor is using. The tutorial involves creating a simple Single Page Application in Angular using Ty ...

Leverage push notifications and utilize multiple service workers with an Angular Ionic 5 progressive web app, designed for optimal performance on Web, Android

Currently facing an issue with my Ionic/Angular Capacitor PWA. In order to enable PUSH NOTIFICATIONS for Web, Android, and IOS platforms, I have focused on setting it up for Web first. The Angular app prompts users for permission to receive notifications ...

Always directing to the initial page upon refreshing the browser in Angular's secondary route

In my app, there is a default component called StartComponent, accessed through the Angular router's start route. Therefore, in the browser address bar, it appears as myhost/start. Upon navigating to the second route, the app logic takes me to Second ...

Sharing data between two components in an Angular2-Meteor application

I am currently working with angular2-meteor. When attempting to transfer a value between two components (updating the value in the first component triggers an event in the second component where the new value is used), I have two methods available: The ...

Encountering a JSON error in Ionic 3 due to a circular structure conversion

Hello everyone, I am a beginner in Angular 2+ and Ionic 3. I am currently attempting to submit a login form from my Ionic 3 app to my ASP.NET Web API application for token-based authentication. However, I keep encountering the following error: converting c ...

How to replace/redirect the import statement in TypeScript from { X } to 'Y'

My situation involves an external library known as Y, which was installed using npm and loaded from the node_modules directory. This library is hosted on GitHub and currently being utilized in my project in the following manner: import { X } from 'Y& ...

Discovering the highest value within an array of objects

I have a collection of peaks in the following format: peaks = 0: {intervalId: 7, time: 1520290800000, value: 54.95125000000001} 1: {intervalId: 7, time: 1520377200000, value: 49.01083333333333} and so on. I am looking to determine the peak with the hig ...

Are there any notable purposes for using the `.d.ts` file extension beyond just improving code readability?

Within my project, I have a file named shims-vue.d.ts located in the src folder: declare module '*.vue' { import type { DefineComponent } from 'vue' const component: DefineComponent<{}, {}, any> export default component } I ...