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

Angular HTML layout designed for seamless interaction

<div class ="row"> <div class ="col-md-6"> Xyz </div> <div class ="col-md-6"> Abc </div> </div> Using the code above, I can easily create a layout with two columns. Th ...

There is no link between the two containers

I am facing an issue where two containers need to connect with each other. However, when attempting to fetch data from one container, I encounter an ENOTFOUND error. Surprisingly, this code functions properly on my local system but fails within the contain ...

What is the best way to transform typescript defined string types into an array of strings?

I'm attempting to extract all defined types from a variable in a constructor. export interface TestType { resultType?: 'NUMBER' | 'STRING' | 'DATE' | 'ENUM' | 'AMOUNT' ; } My expectation is to achie ...

Learn how to incorporate a 'Select All' feature as the primary choice in DevExtreme SelectBox with Angular 15 through Html coding

We are looking to replicate the following basic HTML select in Angular 15 using a dropdown control from DevExpress known as dx-select-box <select ng-model="selectedVal" ng-change="selectedValueChanged()"> <option value=&q ...

Angular HTTP Patch method requires explicitly defined HTTP options as input parameters

I encountered a challenge with using Angular's HTTP patch method and noticed that the overloaded function patch(url, body, options) only accepts hardcoded values for HTTP options. An example of a hardcoded approach that works: patchEntity(id: number) ...

Create a placeholder class for the Form Builder group component within an Angular application

Currently, I am in the process of creating numerous new forms. For instance: constructor(private formBuilder: FormBuilder) { this.userForm = this.formBuilder.group({ 'name': ['', Validators.required], 'email&apo ...

After upgrading to Angular 15, the Router getCurrentNavigation function consistently returns null

Since upgrading to angular 15, I've encountered a problem where the this.router.getCurrentNavigation() method is returning null when trying to access a state property passed to the router. This state property was initially set using router.navigate in ...

Tips for making a dynamic link button using Angular

I am currently working on creating responsive buttons that will navigate to specific pages using Angular routing. Here is my routing configuration: const routes: Routes = [ { path: 'home', component: HomeComponent}, { path: ' ...

How to successfully utilize TypeScript ES6 modules and RequireJS for registering Angular elements

I am in the process of updating a current Angular application that uses AMD with TypeScript 1.5 ES6 module syntax. Our modules are currently stored in separate files, and the main "app" module is defined like this... define('app', ['angular ...

Patience is key until Angular completes loading the issue

I have been experimenting with a similar method to the one Salim shared in this post Testing AngularJS with Selenium However, every time I run it, the script consistently waits for the "webdriver wait" period. It seems like the boolean check always retur ...

Steer clear of using enum values in typescript to prevent potential issues

I am looking to iterate through an enum type in order to populate options within a react component. Below, you will find the specific enum and a function that retrieves its keys and values. export enum TaskType { daily, weekly, monthly, yearly } ...

Live Reload isn't functioning

I recently came across some videos where the app automatically recompiled whenever any changes in the code were made. Typically, when ng serve is run, it should display a message like: Live reload server on ... However, for some reason this feature do ...

The function Array.foreach is not available for type any[]

I'm encountering an issue where when I attempt to use the ".forEach" method for an array, an error message stating that the property 'forEach' does not exist on type 'any[]' is displayed. What steps can I take to resolve this probl ...

Angular Reactive Forms may not properly update other inputs when binding a control to multiple inputs

While working with reactive forms, I encountered an issue where accessing the same control in multiple inputs seemed to result in one-way data binding (input-to-model). If I make edits in one input, it updates the model correctly but does not refresh the o ...

What is the best method for storing objects in Firebase in order to easily rearrange them at a later time?

My list looks something like this: {"ids": [ { "id1": { "name": "name1", "lastname": "lastname1" } }, { "id2": { "name": "name2", "lastname": "lastname2" } }, { "id3": { "name": "name3", "l ...

Tips for utilizing ngIf based on the value of a variable

Here is the code from my file.html: <button ion-button item-right> <ion-icon name="md-add-circle" (click)="save();"></ion-icon> </button> The content of file.ts is: editmode = false; I am trying to achieve the foll ...

Is it not possible to access the width and height of an element using ViewChild, unlike what is suggested in other responses

I've encountered an issue with my Angular component. The HTML code for the component, before any TypeScript is applied, looks like this: <svg #linechart id="chartSpace"></svg> Wanting to create a responsive webpage featuring a line chart ...

Encountering an error in TypeScript and ng2 rc.1: Error message (20, 15) TS2304 indicates that the name 'module' cannot be found

Having trouble with TypeScript and ng2 rc.1 - getting Error:(20, 15) TS2304: Cannot find name 'module'. I encountered this issue when trying to use a directive of the module in my code: @Component({ selector: 'Notes1', moduleI ...

I'm encountering difficulty trying to set up sweetalert2 in Angular

Please provide an image description I'm facing a problem and I need assistance. Despite following various installation guides, I have been unable to find a resolution. Please provide an image description ...

Removing Firebase Users using Angular2/Ionic2

I'm currently working with Ionic2/Angular2 and I've been searching for a guide on deleting users from Firebase. If anyone has any useful examples, I would greatly appreciate the assistance. Thank you. ...