Angular messaging service error TS2769: There is no overload that fits this call

Currently, I am attempting to utilize a messenger service to send products to the cart component. Within the 'Product' class, there are various product attributes stored. Although I managed to successfully log the product to the console in the cart component, encountering an issue when establishing the subscribe method. Specifically, the 'product: Product' line within the subscribe method of the cart component triggers the appearance of the following error message:

src/app/cart/cart.component.ts:31:7 - error TS2769: No overload matches this call.
  Overload 1 of 5, '(observer?: NextObserver<unknown> | ErrorObserver<unknown> | CompletionObserver<unknown> | undefined): Subscription', gave the following error...
    

Below is my messenger service file for reference:

import { Injectable } from '@angular/core';
import {Subject, Observable} from 'rxjs';
import { Product } from './product';

@Injectable({
  providedIn: 'root'
})
export class MessengerService {
  subject = new Subject();

  constructor() {}

  sendMsg(product: any) {
    console.log(product);
    this.subject.next(product);
  }

  getMsg() {
    return this.subject.asObservable();
  }
}

Here is the content of the cart component file:

import { Component, OnInit } from '@angular/core';
import { MessengerService } from 'src/app/messenger.service';
import { Product } from 'src/app/product';
import { CartItem } from 'src/app/cartitem';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-cart',
  templateUrl: './cart.component.html',
  styleUrls: ['./cart.component.css']
})
export class CartComponent implements OnInit {
  cartItems: any[] = [];

  cartTotal = 0;

  constructor(private msg: MessengerService) {}

  ngOnInit() {
    this.msg.getMsg().subscribe((product: Product) => {
      this.addProductToCart(product);
    });
  }

  addProductToCart(product: Product) {
    console.log(product);
    this.cartItems.push({
      productId: product.id,
      productName: product.name,
      qty: 1,
      price: product.price
    });

    this.cartTotal = 0;
    
    this.cartItems.forEach(item => {
      this.cartTotal += (item.qty * item.price);
    });
  }
}

Answer №1

Kindly specify the Subject's type. subjectType = createSubjectType();

Answer №2

To fix the issue, simply include the Subject type. subject= new Subject(); This should solve the problem.

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

Can you pass a generic type as a parameter for another generic in Java?

Simply provide a generic type like a callback: type FUNC<ARG,RET, F> = (arg: ARG) => F<RET>; type PROMISE<T> = Promise<T>; type IDENT<T> = T; type A = FUNC<number, void, IDENT>; type A_PROMISE = FUNC<number, void, ...

Angular Checkbox Click EventLearn how to handle click events on

How can I toggle the visibility of a form using ngIf when a click event is triggered by a checkbox? Below is the code for my column header and column values: <th><label class="btn btn-filter"> <input type="checkbox" ...

Tips for accessing the return value from a method outside of its containing function

Having recently started using Angular, I'm encountering an issue with retrieving a return value from a function that I have implemented within another one. private validateKeyterm(): boolean { const val = this.form.value.term; if ...

Duplicate Component Names Detected in Angular 2

Just starting out with Angular 2 and I'm working on an app. I've organized my components into folders based on their functionality, here's how it looks: - app --components ---users ----create ----edit ---collaborations ----create ----edit ...

Here's a revised version: "How to link a lambda layer with a function in a serverless.ts file using the

When working with the serverless framework using the typescript template, a serverless.ts file is generated. I am currently integrating lambda layers with existing functions and encountering a typescript error. The error message reads: "Type '{ Ref: ...

Images in Angular Firebase causing scroll problems in Chrome

In regard to Angular 6, a common issue arises with slow image loading specifically in Chrome, not other browsers. The project utilizes Firebase and the snapshotchange method to fetch images for the Angular project. Image URLs used are like this: . The iss ...

When a user clicks on the download link, it redirects them to the homepage in Angular

When using Angular 6 and the downloadFile method to download an Excel sheet from the WebAPI, everything runs smoothly. A dialog box opens up asking to save the file on the drive, but then it unexpectedly navigates me back to the home page. This redirects ...

Is it possible to derive a TypeScript interface from a Mongoose schema without including the 'Document' type?

Using ts-mongoose allows me to define interfaces and schemas for my data in one place. I then export them as a mongoose schema along with the actual interface. The challenge I'm facing is finding a simple way to extract that interface without includi ...

Accessing information from req.files in a TypeScript environment

I am currently using multer for uploading images. How can I retrieve a specific file from req.files? Trying to access it by index or fieldname has been unsuccessful. Even when I log it, I see that it's a normal array, so I suspect the issue may be rel ...

Maintaining scroll position in React Router v6

My website's homepage displays a user's feed. When a user clicks on one of the feed cards, they are taken to a different URL. However, when the user returns to the homepage, it automatically scrolls to the top. I am looking for a way to preserve ...

What is the equivalent of specifying globalDevDependencies for npm @types packages in typings?

I am looking to update a project using tsc@2 and remove typings from my toolchain. Updating common dependencies is easy as they are listed in my typings.json file: "dependencies": { "bluebird": "registry:npm/bluebird#3.3.4+20160515010139", "lodash": ...

The pipe operator in Angular is failing to function as intended

I encountered an error while using the replace operator in Angular. Can someone help me identify the issue? Check out this link for more information ...

What is the most efficient way to apply multiple combinations for filtering the information within a table?

I'm facing an issue with my Angular project. I have 4 select boxes that allow users to apply different filters: office worker project name employee activities The problem I'm encountering is the difficulty in predicting all possible combination ...

Using the Capacitor plugin for Firebase Auth, log in to Azure AD B2C with Ionic/Angular

I have been trying to authenticate with Microsoft using a Capacitor plugin, but I haven't had any success so far. I carefully followed the instructions in this documentation and made sure everything is well configured. Could you please guide me on w ...

The upcoming construction of 'pages/404' page will not permit the use of getInitialProps or getServerSideProps, however, these methods are not already implemented in my code

Despite my efforts to search for a solution, I have not found anyone facing the same issue as me. When I execute next build, an error occurs stating that I cannot use getInitalProps/getServerSideProps, even though these methods are not used in my 404.tsx f ...

What is the best way to extract the inner text from an element within a QueryList<T>?

function addGoatToVaccinationGroup(goatObject: {earTag:string, id:number}){ for (let i = 0; i < this.vaccineQueue.length; i++){ if (this.vaccineQueue[i].earTag === goatObject.earTag){ this.vaccineQueue.splice(i, 1); ...

What are the steps to implement SignalR Stream in an ASP.NET Core Angular application?

Attempting to utilize SignalR stream for sending real-time data to clients and displaying it on an Angular component's template. Below is a snippet of my code, where this function is linked to a button (click) event in the template: getMessage(m ...

Facing an issue with the ng2-carousel component where the left and right arrow icons are

Currently employing ng2-carouselamos Visit the ng2-carouselamos npm page here After duplicating the provided HTML template, I have encountered issues with clickable events not functioning properly. The absence of a TypeScript file in the documentation ma ...

Having trouble accessing child directives in Angular 2 using @ContentChildren

I'm facing an issue getting nested directives from a parent directive, as @ContentChildren is not being populated. The main goal is to implement lazy-loading for images, where each image is a nested directive within the parent directive. For instan ...

Issue with setting cookies in Node.js using Express

Recently I made the switch from regular JavaScript to TypeScript for my project. Everything seems to be functioning properly, except for session handling. This is the current setup of my project: Server.ts App.ts /db/mongo/MongoHandler.ts and some other ...