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.