The error message "Property 'then' is not available on type 'void' within Ionic 2" is displayed

When retrieving data from the Google API within the function of the details.ts file, I have set up a service as shown below. However, I am encountering a Typescript error stating

Property 'then' does not exist on type 'void'
.

this.typeApi.getTypeDetails(baseUrl).then(data => {
});

In the type-api.service.ts file, I am fetching data from the Google API in the following manner:

import { Injectable } from '@angular/core';
import { Http /*, Response*/ } from '@angular/http';
import 'rxjs/Rx';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class TypeApi {

constructor(public http: Http ) {}

getTypeDetails(PlaceUrl){
        this.http
        .get(PlaceUrl)
        .map(res => res.json())
        .subscribe(
            (data) => data,
            (err) =>  err); // Handle if fails
}

}

And in the package.json file:

"dependencies": {
"@angular/common": "2.4.8",
"@angular/compiler": "2.4.8",
"@angular/compiler-cli": "2.4.8",
"@angular/core": "2.4.8",
"@angular/forms": "2.4.8",
"@angular/http": "2.4.8",
"@angular/platform-browser": "2.4.8",
"@angular/platform-browser-dynamic": "2.4.8",
"@angular/platform-server": "2.4.8",
"@ionic-native/core": "3.1.0",
"@ionic-native/geolocation": "^3.4.4",
"@ionic-native/launch-navigator": "^3.4.4",
"@ionic-native/splash-screen": "3.1.0",
"@ionic-native/status-bar": "3.1.0",
"@ionic/storage": "2.0.0",
"font-awesome": "^4.7.0",
"ionic-angular": "2.3.0",
"ionic2-rating": "^1.2.0",
"ionicons": "3.0.0",
"rxjs": "5.0.1",
"sw-toolbox": "3.4.0",
"zone.js": "0.7.2"
  },
"devDependencies": {
"@ionic/app-scripts": "1.1.4",
"typescript": "2.0.9"
},

Answer №1

To ensure proper execution, it is recommended to return a Promise from the method getTypeDetails, as shown below:

getTypeDetails(PlaceUrl){
    return this.http
        .get(PlaceUrl)
        .map(res => res.json())
        .toPromise();
}

However, returning just the Observable is often considered the more efficient approach:

getTypeDetails(PlaceUrl){
    return this.http
        .get(PlaceUrl)
        .map(res => res.json());
}

Then, use the following code snippet to subscribe to the data:

this.typeApi.getTypeDetails(baseUrl).subscribe(data => {
});

Answer №2

I agree with Gunter's suggestion. Additionally, I recommend setting the method (function) return type whenever possible to indicate the type of result the caller will receive. For example:

Assuming that your TypeApi will be used by multiple callers.

public getTypeDetails(apiUrl: string) : Observable<any>{
       return this.http.get(apiUrl)
          .map(res => res.json())
          .catch((error) => this.handleError(error)); 
}

//Here is an example of the handleError function:

private handleError (error: any) {
    // You could delve deeper into the error for a more detailed message or utilize a remote logging system
    let errMsg = (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : 'Server error';
    console.error(errMsg); // log errors to the console
    return Observable.throw(errMsg);
  }

When calling this method, you must subscribe to the returned result:

this.typeApi.getTypeDetails(theUrl).subscribe(result => {
    // This is where you handle success, similar to handling success in AJAX calls
    // Make use of the received data
   }, 
   error => {
       // This is where you handle errors, similar to how errors are handled in AJAX calls
       // Handle the error appropriately
   }
);

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

Steps for converting an Array of tuples into a Union of Tuples

I am attempting to develop a custom type that, when given an array of tuples as input, will generate the union of each index within the tuple. This may not be the most accurate terminology, but I hope you understand what I mean. const entries = [["name", ...

Converting the following ngRx selector to a boolean return – a guide

I am currently using the following filter to retrieve a list of data within a specific date range. I have implemented logic in the component where I check the length of the list and assign True or False to a variable based on that. I am wondering if ther ...

Understanding authorization and user roles within an Angular 2 application utilizing Microsoft Graph

As a newcomer, I am in the process of developing a CVThèque application using angular 2 and .net core. For authentication purposes, I have integrated Microsoft Graph and adal successfully. However, I am unsure how to set up permissions and group roles for ...

Encountered a Runtime Error: Uncaught promise rejection - couldn't locate removeView

I am facing an issue with calling two API calls on the same page. When I use only one API call, everything works fine. However, when I try to make two API calls on the same page, I encounter the following error at runtime: Error Uncaught (in promise): r ...

Validation of email forms in Angular 5

I have encountered a challenge that I need help with: Using Angular 5 - template driven form In my template, there is an input field with the type email. Here's an example: <input type="email" [(ngModel)]="model.email" #email="ngModel" email /> ...

Creating a primary index file as part of the package building process in a node environment

Currently, I have a software package that creates the following directory structure: package_name -- README.md -- package.json ---- /dist ---- /node_modules Unfortunately, this package cannot be used by consumers because it lacks an index.js file in the r ...

How can we limit the CSS properties that can be used in an interpolated manner by defining a restricted TS type for CSS props based on emotions?

When dealing with emotions, how can we specify a restricted TS type for the css prop to only allow certain css properties to be interpolated? For instance, consider the following scenario: // This is considered valid css = {{ color: 'white', ...

Initiating a GET request to execute an SQL query with specified parameters

Let me provide some background information. I am currently using Angular for the frontend and Express for the backend, while also learning how to effectively utilize both technologies. In my application, there is a parent component that generates a group ...

What is the process for configuring the directive to establish a drag-and-drop area within Angular?

I am currently working on implementing a file drag and drop zone in Angular. I have created the dropzone.directive and added it to the declarations in app.module.ts. While my code compiles and launches successfully, I am facing an issue where the HTML doe ...

In a Typescript Next Js project, the useReducer Hook cannot be utilized

I'm completely new to Typescript and currently attempting to implement the useReducer hook with Typescript. Below is the code I've written: import { useReducer, useContext, createContext } from "react" import type { ReactNode } from &q ...

Verify the accuracy of each object in an array by comparing it to an enum and confirming its validity

I am trying to determine how many matches/true values there are based on the values of all objects in an array, compared to an enums value. My array of objects is structured like this: const jobs = [{ description, title, }... ] In addit ...

Transform TypeScript class into an object

Is there a way to transfer all values from one typescript class, Class A, to another matching class, Class B? Could there be a method to extract all properties of Class A as an object? ...

Discovering updates to a read-only input's [ngModel] binding in an Angular 2 directive

One issue I'm facing is with a directive that sets the height of a textarea dynamically based on its content: @Directive({ selector: '[fluidHeight]', host: { '(ngModelChange)': 'setHeight()' } }) export class ...

I encountered an error while trying to deploy my next.js project on Vercel - it seems that the module 'react-icons/Fa' cannot be found, along with

I'm currently in the process of deploying my Next.js TypeScript project on Vercel, but I've encountered an error. Can someone please help me with fixing this bug? Should I try running "npm run build" and then push the changes to GitHub again? Tha ...

Issue with PixiJS: Clicking on a line is disabled after changing its position

Trying to create clickable lines between nodes using Pixi has been a bit of a challenge for me. To ensure the line is clickable, I've extended it in an object that incorporates Container. The process involves finding the angle of the line given two p ...

Tips for saving multiple pieces of data in a single field with Laravel

Is it possible to save multiple data at once using a simple form? controller $status= new PostTable(); $status->language = $request->language; blade <input type="checkbox" value="hindi" name="language[]" id="language"> Hindi model pro ...

Angular Universal causes SASS imports to malfunction

Check out this sample app that you can download to see the issue in action: https://github.com/chrillewoodz/ng-boilerplate/tree/universal I am currently working on implementing angular universal, but I'm encountering an error with a SCSS import in o ...

Enhance the appearance of the table footer by implementing pagination with Bootstrap Angular6 Datatable styling

I utilized the angular 6 datatable to paginate the data in a table format. https://www.npmjs.com/package/angular-6-datatable Everything is functioning properly, but I am struggling with styling the footer of mfBootstrapPaginator. The items appear stack ...

Is it possible to determine the specific type of props being passed from a parent element in TypeScript?

Currently, I am working on a mobile app using TypeScript along with React Native. In order to maintain the scroll position of the previous screen, I have created a variable and used useRef() to manage the scroll functionality. I am facing an issue regardi ...

Utilize JavaScript libraries in a TypeScript project

Looking to integrate a payment system called iyzico into my project. The iyzico payment library can be found here. However, there are no types available for it. How can I utilize this library in my Node.js TypeScript Express backend project? I attempted t ...