After importing RxJS, the error "toPromise is not a function" is encountered

I am trying to utilize the Promise operator

Firstly, I imported rxjs:

import 'rxjs/add/operator/toPromise';

then in my component, I implemented it

ngOnInit() {
    this.EJnames= this.dataservice.getResults();
    this.generalinfosservice.getResults("nothing").then(data=>{this.data=data; console.log(data)}); //Log 1
 console.log(this.data); // log 2
  }

An error occurred stating:

ERROR TypeError: this.generalinfosservice.getResults(...).toPromise is not a function

I have double-checked my Package.json, and confirmed that I have rxjs:

"rxjs": "^5.1.0",

Here is the generalinfosservice.getresults function

import { Injectable } from '@angular/core';
import { RmpmService}  from '../../shared/abstract-classes/service'
import { HttpClient } from '@angular/common/http';

@Injectable()
export class GeneralinfosService extends RmpmService {

  constructor(public httpClient: HttpClient) { }
    public getResults(body) {
        let url;
        let mockUrl
            url = '/obtenirNomenclatures/typeNomenclatures/';
            mockUrl = 'assets/data/group.json';

    return this.post(url, mockUrl, body);
    }
}

and post function which is within an abstract class :

post( url, mockUrl, body) {
    if( environment.mocked ) {
        return this.httpClient.get( mockUrl ).toPromise().then( data => { return data} );
    } else {
        return this.httpClient.post( url, JSON.stringify( body ) )
            .toPromise()
            .then( data => {
                return data;
            }, ( err: any ) => {
                return this.handleError( err.message );
            } );
    }
}

PS: I am operating in a mocked environment

Answer №1

Instead of calling this.post() within getResults(), you should be calling this.httpClient.post(). This ensures that you are invoking the correct method within your GeneralInfoService class.

Answer №2

// This import is necessary for the fixes I made below to function properly:
import { Observable } from 'rxjs/Observable';

// Your current method for "post".
post( url, mockUrl, body) {
    if( environment.mocked ) {
        // The promise you are returning does not have another promise attached to it. You are only returning the "data" value, which lacks a ".then()" function.
        // return this.httpClient.get( mockUrl ).toPromise().then( data => { return data} );
        
        // This is the correct way to do it:
        return this.httpClient.get( mockUrl )
            .toPromise()
            .then(( data ) => Observable.of( data ).toPromise());
    } else {
        return this.httpClient.post( url, JSON.stringify( body ) )
            .toPromise()
            .then(
                ( data ) => Observable.of( data ).toPromise(), 
                ( err: any ) => this.handleError( err.message )
            );
    }
}

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

Error encountered when utilizing a mixin in TypeScript due to a parameter issue

Recently, I delved into learning Typescript and decided to experiment with the mixin concept. The code snippet below may seem trivial, but it's all part of the learning process. Surprisingly, everything runs smoothly except for line 42, myInput.sendKe ...

Node.js and Typescript encountering issues resolving module paths

I am brand new to both Express and Typescript. I recently inherited a project that utilizes express for an API. I need to make some modifications, but I am having trouble transpiling the code. I have exhausted all my options and now I'm seeking help h ...

Incorporate data binding within ngFor

When working with an array in HTML using *ngFor, I need to calculate the total value of the array without utilizing the .ts file. The total value should be displayed in a separate row. <ion-grid> <ion-row *ngFor="let item of dailyDays"> ...

I'm having trouble importing an image into my typescript file as it keeps showing a "module not found" error message. Can anyone

I am new to working with TypeScript and I have encountered an issue when trying to import an image from my assets folder. Despite having the image stored in a designated folder, Visual Studio Code notifies me that it cannot find the module. Here is the er ...

How can you set a checkbox to be selected when a page loads using Angular?

On page load, I need a checkbox to already be 'checked', with the option for the user to uncheck it if they want. Despite trying to add [checked]="true" as recommended in some Stack Overflow answers, this solution is not working for me. <label ...

The command "npm start" is currently experiencing issues, showing an error message stating that it failed at the start script for the project

I have been using this link as an example to learn Angular. However, when I try to run npm start, it shows an error. I have looked for solutions and they suggest updating either npm or Angular versions, but I am already using the latest versions: npm -v = ...

What is the best way to declare a TypeScript type with a repetitive structure?

My data type is structured in the following format: type Location=`${number},${number};${number},${number};...` I am wondering if there is a utility type similar to Repeat<T> that can simplify this for me. For example, could I achieve the same resul ...

Transform an Array into a String using Angular

Is there a more efficient way to extract all the state names from the array (testArray) and convert them to strings ('Arizona','Alaska','Florida','Hawaii','Gujarat','Goa','Punjab'...)? ...

The expiration date is not considered in JWT authentication using passport-jwt

I have been working on implementing an authentication system using JWT token in Express, utilizing passport-jwt and jsonwebtoken. Everything is functioning correctly at the moment, however, I am facing an issue where the token remains valid even after its ...

Bring in all subdirectories dynamically and export them

Here is what I currently have: -main.js -routeDir -subfolder1 -index.js -subfolder2 -index.js ... -subfolderN -index.js Depending on a certain condition, the number of subfolders can vary. Is there a way to dynam ...

Unable to locate angular moment components

I encountered an error while trying to build my angular project using npm start. I attempted to install dependencies using the yarn command, but it didn't solve the issue. Below is the error message that I am receiving: ERROR in ./src/AppPreBootstra ...

Encountering an unexpected termination error when using Typescript, pg, Express, and Psql within a Docker container: "Error: Connection terminated unexpectedly"

I am facing an issue with connecting to my database running on a Docker container using a postgres image: docker run --name postgres-container -p 2345:2345 -e POSTGRES_PASSWORD=password123 -e POSTGRES_USER=admin -d postgres The TypeScript code I have is i ...

What could be the reason for TypeScript allowing the injection of an invalid type?

I have the following objects and classes that demonstrate dependency injection: abstract class Animal { speak(): void {}; } class Dog implements Animal { speak(): void { console.log('Woof woof'); } } class Cat implements Ani ...

There was an error reported by TypeScript stating that Nest.js is not considered a module

During the development of my project using Nest.js, I came across an error that I couldn't find a solution for. The issue arises when I try to export a function from one file and import it into a controller. Even though the function is exported correc ...

Is Typescript compatible with the AWS Amplify Express API?

I've been struggling to set up my Amplify API in TypeScript and then transpile it to JavaScript. I know it sounds like a simple process, but I could really use some guidance on how to do this effectively. So far, I haven't progressed beyond the ...

Implementing RTKQuery queryFn in TypeScript: A comprehensive guide

Important update: The issue is now resolved in RTKQuery v2 after converting to TypeScript. See the original question below. Brief summary I am encountering an error while trying to compile the TypeScript code snippet below. Tsc is indicating that the r ...

Sorting the material table based on the column IDs, which usually correspond to the column names, may not align with the properties of the data

.ts this.displayedColumns = [ { key: 'id', header: '#' }, { key: 'fullname', header: 'Full name' }, { key: 'email', header: 'email' }, { key: 'roleName', header: ...

Dealing with compilation errors in TypeScript

I'm working on a simple TypeScript program that looks like this - const users = [{ name: "Ahmed" }, { name: "Gemma" }, { name: "Jon" }]; // We're trying to find a user named "jon". const jon = users.find(u => u.name === "jon"); However, wh ...

Tips for capturing your desktop screen within an angular 2+ application

I am in need of a solution to share my desktop screen using Angular 6. I have done some research to find the right package for this feature but have been unsuccessful so far. I came across various packages such as RecordRTC, Aperture, and screen-capture-r ...

Sending emails with Angular 9: A step-by-step guide

Here is a code snippet that demonstrates how to send an email from the server side. I am looking for guidance on how to integrate this code into an Angular 9 application. Any assistance would be greatly appreciated. var nodemailer = require('node ...