Angular 2 Error: TS2322 - The type 'Subscription' cannot be assigned to the type 'Observable<MouseEvent>'

I have implemented the click-outside directive using this plunk --> http://embed.plnkr.co/v7BMUv/

But when I try to compile my TypeScript code, I encounter the following errors:

Error TS2322: Type 'Subscription' is not compatible with type 'Observable'. Property '_isScalar' is missing in type 'Subscription'.

Error TS2339: Property 'unsubscribe' does not exist on type 'Observable'.

This is how my tsconfig.json file looks like:

{
  "compileOnSave": false,
  "compilerOptions": {
    "target": "es6",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "suppressImplicitAnyIndexErrors": true,
    "noImplicitAny": false,
    "noEmitOnError": false
  },
  "exclude": [
    "node_modules",
    "wwwroot"
  ]
}

The piece of code causing these errors is as follows:

ngOnInit() {
    this.globalClick = Observable
      .fromEvent(document, 'click')
      .delay(1)
      .do(() => {
        this.listening = true;
      }).subscribe((event: MouseEvent) => {
        this.onGlobalClick(event);
      });
  }

How can I resolve this issue?

Answer №1

The issue lies within the code in click-outside.directive.ts. When using Observable.subscribe, it returns a Subscription (inside the ngOnInit method), not another Observable. Therefore, the data type of private globalClick should be changed to Subscription.

Without specifying data types, it may seem like everything is functioning correctly, and with plunker not displaying type errors, it seems to work fine. However, when compiling with tsc, an error will occur because you are trying to assign a Subscription object to an Observable.

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

Filling MatTables using asynchronous rows and promises

Is there a way to asynchronously populate the rows of a MatTable with data from a collection of objects? I have a list containing each object's URL and I want to fill in the data as it loads, even if the rows are initially empty. This is my approach: ...

What methods can be used in Angular 2 to delete and update row data through HTTP calls?

I am currently working on implementing employee data manipulation functionalities in an Angular application. While I have successfully managed to add new data to the array, I am facing challenges with updating and deleting existing data. Could someone pro ...

How can I show the localStorage value in an HTML5 template using Angular2?

I have two keys stored in localStorage and I want to display one of them on my template. I'm having trouble accessing these values. I even created an interface specifically for storing the value of the currentUser key from localStorage. How should I g ...

After restoring my Windows system, I encountered an issue with locating the typescript.js module for my Angular app development. I am currently troubleshooting the build

My PC had some issues, so I decided to restore Windows to an older restoration point. However, after doing this, I encountered an error while trying to build my Angular App: C:\Udemy\AngularDeCeroAExpertoEdicion2021\03-paisesApp>npm run ...

Is it possible to use string indexes with jQuery each method in Typescript?

When running a jQuery loop in Typescript, I encountered an issue where the index was being reported as a string. $.each(locations, (index, marker) => { if(this.options && this.options.bounds_marker_limit) { if(index <= (this.opt ...

Angular type error: Attempting to assign a value of type 'string' to a variable declared as type 'string[]' is not allowed

As a newcomer to Angular, I am currently working on building an electron app with Angular 6. My objective is: 1. Implementing SupportInformationClass with specific definitions 2. Initializing the component to populate the definitions from electron-settin ...

Packaging an Angular project without the need for compiling

In order to enhance reusability, I structured my Angular 6 Project into multiple modules. These modules have a reference to a ui module that contains all the style sheets (SASS) as values such as: $primary-text-color: #dde7ff !default; Although this app ...

Automatic type inference is activated while employing intricate "isEmpty" verification

I have created a customized function similar to Ramda's isEmpty, tailored to meet my specific requirements: /** * Checks if a value is empty. * Returns true for null, undefined, empty strings, empty Sets, empty Maps, and objects without properties. ...

Implementing an event listener within a knockoutjs custom directive

I have extensive experience as a knockout user, but I am currently struggling to achieve a specific scenario. For the past few days, I have been trying to create a system within a knockout component that allows observables to translate themselves into diff ...

Execute the render function of the components that have been passed as

I've been grappling with a challenge lately - figuring out how to invoke a passed component's render function within another function. Let's say I have two functions named A and B: export const A = (value: any) => { return ( <div& ...

Managing absence of ID field in Prisma and retrieving data from API request

When fetching data from an API, my approach looks like this: async function getApiData() { const promises = []; for (let i = 0; i < PAGE_COUNT; i++) { const apiData = fetch(...); } const apiData = await Promise.all(promises); return apiDat ...

Harmonize the connectivity between an Angular - .NET application and the Google Calendar API

I am currently working on integrating the Google Calendar API into my angular .NET application using OAuth2. The goal is to allow each user to see their own calendar as soon as they log in. One idea I have is to save the generated code into our database f ...

Using Angular to convert multiple JSON objects into objects on a map

I am facing a challenge with merging multiple JSON objects into one unified object. The issue lies in the fact that these JSON objects have mismatched "keys". Could you provide assistance in finding a solution to this dilemma? Here is an example of JSON ...

Why does the ReactJS MaterialUI Modal fail to update properly?

Recently, I encountered a curious issue with my Modal component: https://i.stack.imgur.com/dkj4Q.png When I open the dropdown and select a field, it updates the state of the Object but fails to render it in the UI. Strangely, if I perform the same action ...

How can we design a Protobuf structure for a map that contains an array of objects as the value?

I need help with encoding a map in a protobuf format. Here is an example of the map: const newVisMap = new Map<number, IOutput[]>(); The map contains an array of objects that share a common interface, as shown below (with one optional property): int ...

Is there a validation issue with the number input in Angular?

I'm encountering an unusual issue while trying to validate input[type=number] in Angular 7 and I'm hoping someone can provide some assistance. <input class="form-control" type="number" name="entranceFee" min="0" [(ngModel)]="entranceFee" ...

Screen the reaction of a stream of data and store it in a designated memory location

I am facing an issue with filtering the results of a service that returns an ApiResponse object containing a vector of Client objects. While the service itself is functioning correctly and data is being received properly, I am unable to filter the results ...

The CORS policy is causing a blockage for the front-end application due to the Spring Boot backend

Currently working with Spring Boot and Angular. I have included the cross-origin annotation in my code to allow access from my Angular localhost port, but unfortunately, I am still encountering the following error: https://i.sstatic.net/4uDuv.png Here is ...

Having trouble resolving rxjs/operators when using ngx-datatable?

I am attempting to integrate ngx-datatable into my Angular-2 project. I have followed all the steps outlined here, but I encountered the following error: ERROR in ./~/@swimlane/ngx-datatable/release/index.js Module not found: Error: Can't re ...

Finding out the exact number of pixels a user will scroll when using the mouse wheel in Javascript

Is there a way to calculate the number of pixels that will be moved by the vertical scroll bar when a user scrolls using the mouse wheel in JavaScript? In my situation, the user's scrolling will result in an offsetTop change between 200px to 1000px, ...