A mistake occurred: The function this.http.get(...) is not supported with the method map within BookService.push

Below is my code for the books service:

import { Injectable } from '@angular/core';

import { Http, Response } from '@angular/http';

import { Observable } from 'rxjs';

import { map } from 'rxjs/operators';

//import {catch} from 'rxjs/operator';

//import { toPromise } from 'rxjs/operator';

import { Book } from './book';

//import 'rxjs/add/operator/map';

import 'rxjs/add/operators/catch';

import 'rxjs/operators/toPromise';



@Injectable()
export class BookService 
{
    url = "http://localhost:4200/assets/data/books.json";

    constructor(private http:Http) { }

    getBooksWithObservable(): Observable<Book[]> 
    {
        return this.http.get(this.url)
                .map(this.extractData)
                .catch(this.handleErrorObservable);
    }
    getBooksWithPromise(): Promise<Book[]> 
    {
        return this.http.get(this.url).toPromise()
            .then(this.extractData)
            .catch(this.handleErrorPromise);
    }
    private extractData(res: Response) 
    {
        let body = res.json();
        return body;
    }
    private handleErrorObservable (error: Response | any) 
    {
        console.error(error.message || error);
        return Observable.throw(error.message || error);
    }
    private handleErrorPromise (error: Response | any) 
    {
        console.error(error.message || error);
        return Promise.reject(error.message || error);
    }   
}

When running the command 'ng serve --open', I encounter the following Error :

ERROR in src/app/book.service.ts(24,12): error TS2339: Property 'map' does not exist on type 'Observable<Response>'.

Another error surfaces in observable.component.ts. Below is the code snippet of observable.component.ts:

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';

import { BookService } from './book.service';
import { Book } from './book';

@Component({

   selector: 'app-observable',

   templateUrl: './observable.component.html'

})

export class ObservableComponent implements OnInit {

   observableBooks: Observable<Book[]>;

   books: Book[];

   errorMessage: String;

   constructor(private bookService: BookService) { }

   ngOnInit(): void {

        this.observableBooks = this.bookService.getBooksWithObservable();               

        console.log('observable');

        alert('observable');


        console.log(this.observableBooks);

        this.observableBooks.subscribe(

            books => this.books = books,

            error =>  this.errorMessage = <any>error);
   }    
}

The error message encountered in this file is as follows:

src/app/observable.component.ts(23,4): error TS2345: Argument of type 'void' is not assignable to parameter of type '(error: any) => void'
.

If anyone can provide a solution to this, it would be greatly appreciated. Thank you in advance.

Answer №1

When working with RxJs, it's important to utilize the map function as a pipable operator.

For example, you can implement it like this:

this.http.get(this.url).pipe(map(this.extractData))
. It's recommended to use this approach instead of importing from rxjs/add/operator/map, especially when working with RxJs versions equal to or greater than 5.X

Additionally, make sure to use HttpClient from @angular/common/http instead of Http.

Answer №2

To address the first issue: The error message 'Property 'map' does not exist on type 'Observable'.' is showing up.

To resolve this problem, you should include the following imports:

import { Observable } from 'rxjs/Observable'; 
import 'rxjs/add/operator/map'; 

As for the second solution:

Consider removing the keyword void from the ngOnInit method:

ngOnInit() {

        this.observableBooks = this.bookService.getBooksWithObservable();               

        console.log('observable');

        alert('observable');


        console.log(this.observableBooks);

        this.observableBooks.subscribe(

            books: any  => this.books = books,

            error: any =>  this.errorMessage = <any>error);
   }    

Answer №3

You could experiment with using import 'rxjs/add/operator/map'; in place of

import { map } from 'rxjs/operators';

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 could be causing the module version discrepancy with the package.json file I created?

Recently, I created a project using create-next-app and decided to downgrade my Next.js version to 12. After that, I proceeded to install some necessary modules using Yarn and specified the versions for TypeScript, React, and others. During this setup, I b ...

Facing a Bad Request error while trying to submit a Django Rest Framework Post request that appears to be valid, but is requiring a

Currently, I am in the process of creating a new instance of the SearchNeighborhood object and establishing a connection with an already existing SearchCity object through a POST request. The models I have set up are as follows: class SearchCity(models.M ...

Tips on transferring key values when inputText changes in ReactJs using TypeScript

I have implemented a switch case for comparing object keys with strings in the following code snippet: import { TextField, Button } from "@material-ui/core"; import React, { Component, ReactNode } from "react"; import classes from "./Contact.module.scss" ...

Encountering an issue with multi ./src/styles.scss during the deployment of my Angular application on Heroku

My attempt to deploy my Angular app on Heroku is resulting in an unusual error. I've experimented with changing the styles path in angular.json, but it hasn't resolved the issue. I suspect it's a path problem, yet I can't seem to corre ...

An unexpected error occurred while running ng lint in an Angular project

I've encountered an issue while trying to run ng lint on my Angular project. After migrating from TSLint to ESLint, I'm getting the following error message when running ng lint: An unhandled exception occurred: Invalid lint configuration. Nothing ...

How can I retrieve List<T> from a Razor Page using TypeScript?

Within my ViewModel, I have an Items collection: public class ItemViewModel{ public List<Item> Items {get;set;} } In the Index.cshtml file: @if(Model.Items != null){ <li><a id="item-id-link" href="#" data-items="@Model.Items"> ...

What is the best way to prevent images from being loaded with broken links?

Currently, I am working on a new feature that involves rendering images from servers. In the process of aligning these images, I noticed an excessive amount of white space due to loading images with broken links. https://i.stack.imgur.com/jO8BR.png Here ...

Leveraging Json data in Angular components through parsing

I am currently developing an angular application where I need to retrieve and process data from JSON in two different steps. To start, I have a JSON structure that is alphabetically sorted as follows: { "1": "Andy", "2": &qu ...

Exploring Opencascade.js: Uncovering the Real Text within a TCollection_ExtendedString

I am currently attempting to retrieve the name of an assembly part that I have extracted from a .step file. My method is inspired by a blog post found at , however, I am implementing it using javascript. I have managed to extract the TDataStd_Name attribut ...

Encountered an issue while trying to install the package '@angular/cli'

Encountered errors while attempting to install @angular/cli using npm install -g @angular/cli. The node and npm versions on my system are as follows: C:\WINDOWS\system32>node -v v 12.4.0 C:\WINDOWS\system32>npm -v 'C ...

Struggling to delete event listeners in TypeScript using object-oriented programming with JavaScript

After researching the issue, I have discovered that the onMouseUp event is being fired but it is not removing the EventListeners. Many individuals facing a similar problem fail to remove the same function they added initially. Upon reading information fr ...

Typescript error code TS7053 occurs when an element is detected to have an implicit 'any' type due to an expression of a different type

I encountered an issue with the provided example. I'm uncertain about how to resolve it. Your assistance would be greatly appreciated. type TestValue = { value: string; }; type FirstTest = { type: 'text'; text: TestValue[]; }; typ ...

Troubles encountered with fetching pre-filled values in Angular form automation

In my project, there is a template driven angular form for the Edit profile section in the app. Data is populated from the API for the form, with fields being empty if no data is available. When a user types new data into the fields, it is successfully pos ...

Utilize a singular loader when simultaneously making numerous HTTP requests in Angular with ngx-ui-loader

After successfully implementing the ngx-ui-loader and setting the NgxUiLoaderHttpModule for all HTTP requests in my project, everything is working fine. However, I have encountered an issue on certain routes where multiple HTTP requests are being executed ...

Angular Apollo client makes generating code from graphql files effortless

After discovering the angular graphql code generator through this source, I decided to implement it in my project for generating graphql types and Query services for angular. The contents of my codegen.yml file are as follows. overwrite: true schema: "ht ...

Issue with retrieving all phone numbers from a contact in Ionic

Hope you're doing well! I'm encountering an issue with Ionic Contacts. Currently, I'm able to retrieve all the contacts using my code but I need help extracting all the phone numbers associated with each contact. For example, if John has 3 ...

Extracting Date and Time Information from matDatepicker in Angular 6 Material

Below is the code snippet present in my html file: <mat-form-field> <input matInput [matDatepicker]="myDatepicker" placeholder="Choose a date" [(ngModel)]="model.value" name="value"> <mat-datepicker-toggle matSuffix [for]="myDatepic ...

Transferring information from parent page to child page using Angular version 8.2.4

As a newcomer to Angular, I am facing a challenge in sharing data between pages upon loading the main page. The structure involves using dynamic forms to generate dynamic pages within the main page. However, when trying to pass data from the main page to t ...

Getting the readonly-item type from an array in TypeScript: A step-by-step guide

Is it possible to create a readonly item array from a constant array? const const basicValueTypes = [{ value: 'number', label: 'Number' },{ value: 'boolean', label: 'Boolean' }]; type ReadonlyItemArray = ??? ...

Pass a delay to an Angular 2 component animation by defining it as an input parameter

Is it possible to set the delay of a component's animation directly from the HTML code? For example: HTML: <circles[delay]="'10000ms'"></circles> Typescript (ts): @Component({ selector: 'circles', templateUrl: ...