The properties required for type 'Subscription' are not present

I encountered an issue in my IDE while trying to run the following code.

Within my component, I am making a call to a service in the ngOnInit method to fetch some data. This service, in turn, calls another service to gather additional information before finally returning the desired data.

Here is the code snippet from the component:

ngOnInit() {
    const token = "abc";
    this.service.getContactPersons(token).subscribe(
      persons => this.contactPersons = persons
    );

  }

And here is the relevant part of the service code:

getContactPersons(token: string): Observable<ContactPerson[]> {
return this.tokenService.getParameters(token).pipe(
      switchMap((data: Params) => {
        return this.http.get<Properties>(
          this.baseUrl + `/abc/${data.param1}/properties/${data.param2}`
        );
      })
    ).subscribe((data: Properties) => data.contactPersons);
}

However, when running the code, I received the error message: "Type 'Subscription' is missing the following properties from type 'Observable': _isScalar, source, operator, lift, and 6 more."

Answer №1

subscribe in RxJS does not directly correspond to the then method used with promises. Unlike promises where you can chain multiple then calls like

somePromise.then(doSomething).then(doSomethingElse)
, you cannot do the same with RxJS streams using subscribe. Instead, if you want to transform the data stream, you should utilize various RxJS operators, such as the map operator:

getContactPersons(token: string): Observable<ContactPerson[]> {
    return this.tokenService.getParameters(token).pipe(
        switchMap((data: Params) => this.http.get<Properties>(
            `${this.baseUrl}/abc/${data.param1}/properties/${data.param2}`)),
        map((data: Properties) => data.contactPersons));
}

Answer №2

If your function getContactPersons currently returns a subscription, simply remove the

.subscribe((data: Properties) => data.contactPersons);
part of the code. This should resolve the issue.

When returning an Observable, it is best practice to either pass along the observable itself or perform operations on it within a pipe() function. Subscribing to an observable multiple times can lead to memory leaks and performance issues for your users.

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

What is the best way to eliminate the alert message "autoprefixer: Greetings, time traveler. We are now in the era of CSS without prefixes" in Angular 11?

I am currently working with Angular version 11 and I have encountered a warning message that states: Module Warning (from ./node_modules/postcss-loader/dist/cjs.js): Warning "autoprefixer: Greetings, time traveler. We are now in the era of prefix-le ...

Oops! A mistake was made by passing an incorrect argument to a color function. Make sure to provide a string representation of a color as the argument next time

Encountering an issue with a button react component utilizing the opacify function from the Polished Library The styling is done using styled-components along with a theme passed through ThemeProvider. Upon testing the code, an error is thrown. Also, the ...

Creating an observer for a multiple selection dropdown in Aurelia: step by step tutorial

In my current setup, I have a dropdown menu that allows users to select a single option. This selection automatically provides me with the filtering value as an observable. Here is how it works: public months: any=[]; @observable public selectedMonth: ...

Creating a HandleCredentialResponse function in Angular version 14 for implementing the "Sign in with Google" feature using Typescript

In the process of building a very simple angular version 14 application, I am working on displaying a 'Sign in with Google button' and incorporating the login functionality. For information about the new method of Sign in With Google, you can re ...

Tips for using a loop variable as an argument in a method call for an attribute reference

Within the html code of my component, I have the following: <div *ngFor="let image of images; let i=index;" class="m-image-wrapper"> <i class="fa fa-times m-delete-img" (click)="removeImage(i, {{image.docname ...

Application: The initialization event in the electron app is not being triggered

I am facing an issue while trying to run my electron app with TypeScript and webpack. I have a main.ts file along with the compiled main.js file. To troubleshoot, I made some edits to the main.js file to verify if the "ready" function is being called. ...

Struggling to display my array data retrieved from the database on my Angular 5 page

I hope everyone is doing well. I am currently facing a problem with retrieving data from Firebase. I have an array within an array and I want to display it in my view, but I am encountering difficulties. Let me share my code and explain what I am trying to ...

What is the syntax for declaring a variable as a string or a function with parameters?

Is it possible to define a variable in TypeScript like a string or as a Function, but with specific parameters? I am aware of how to define a string actionGetData: string; and a function actionLoaded?(event: any, ui: any): void;, but when I try to define ...

inject a dynamic loading icon within the choices of a datalist in an Angular application

<input list="dataUsers" formControlName="user" placeholder="Type the user name" class="form-control form-control-lg" type="text" (ngModelChange)="doSearch($event)"/> <datalist id=&q ...

Dynamically change or reassign object types in TypeScript

Check out the example you can copy and test in TypeScript Playground: class GreetMessage { message: {}; constructor(msg: string) { let newTyping: { textMsg: string }; // reassign necessary this.message = newTyping; this.message.textMsg = msg; ...

Guide on integrating an Angular 10 Component into a cell in Ag-Grid

I am currently working with an Angular10 component, specifically a toggle switch, that I need to integrate into a specific column within my ag-grid cell. Currently, I am using a basic HTML checkbox in the following manner: colDefs: ColDef[] = [ { fiel ...

Issue with passing JSON object from Angular2 HTTP post to MVC 6 controller action

In my current project, I am developing an angular 2 application using asp.net MVC6. The issue I am facing is related to Angular2 Http post method calls in the controller action. It works perfectly fine when there are no parameters/properties involved. Howe ...

Angular does not seem to support drop and drag events in fullCalendar

I am looking to enhance my fullCalendar by adding a drag and drop feature for the events. This feature will allow users to easily move events within the calendar to different days and times. Below is the HTML code I currently have: <p-fullCalendar deep ...

Instructions on transferring JSON data to clipboard using a button

How can I copy JSON data to clipboard using a button click? { "Version": "2012-10-17", "Statement": [ { "Sid": "VisualEditor0", "Effect": "Allow", "Action": [ ... ], "Resource": "*" } ] } I attempted to ...

The Div element triggers a focus event when either the div itself is selected or any nested input field is selected - Angular

Within an Angular application, I have a Div element with an index tab that allows for selection. This Div contains a form with various fields and buttons. My goal is to trigger the focus event on the Div whenever the Div itself is selected or any element w ...

Have I repeated myself in defining my class properties?

Currently, I'm enhancing my understanding of Typescript with the development of a discord.js bot. However, I have come across a piece of code and I am uncertain about its redundancy: import Discord from 'discord.js'; export default class B ...

Incorporating a minute interval in Angular Material's time picker feature

In my Angular 15 project, I am working with this material component. <mat-form-field appearance="outline"> <mat-label>{{'DOCTOR_AREA.START_TIME' | translate}} </mat-label> ...

Connecting Ag Grid with modules

Unable to link with modules as it's not a recognized attribute of ag-grid-angular <ag-grid-angular #agGrid style="width: 100%; height: 100%;" id="myGrid" class="ag-theme-balham" [modules]="modules" [columnDefs ...

Jest is having difficulty locating a module while working with Next.js, resulting in

I am encountering some difficulties trying to make jest work in my nextjs application. Whenever I use the script "jest", the execution fails and I get the following result: FAIL __tests__/index.test.tsx ● Test suite failed to run ...

Could you tell me the kind of theme used in Material-UI version 5?

I've decided to switch my project over to MUI version 5 and embrace the use of emotion CSS. It's come to my attention that I need to incorporate the theme property, but now TypeScript is prompting me for a type definition for it. The current code ...