2

I had created some functions related to Observables in Angular2 for an app I was developing. But since then, I haven't use Angular. So, my working functions related to Observables have to be modified accordingly in order to become functional in Angular8 and I can't get rid of some error messages.

The API from the server returns an array of objects from the database:

router.get('/getEntries, (req, res, next) => {
   db.get().collection('data').find().toArray((err, data) => { res.json(data); });
});

The problem probably is in the entry.service.ts file:

import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {map}        from 'rxjs/operators';
import {Entry}      from '../Classes/entry';

@Injectable()
export class EntryService {

   constructor(private http: HttpClient) { }

   getEntries(): Observable<Entry[]> {
      return this.http.get('http://192.168.1.3:3000/api/getEntries').pipe(map(res => res.json() as Entry[]));
   }

} //end of Service

The app.component.ts is the following:

import {Component, OnInit} from '@angular/core';
import {Entry}             from '../Classes/entry';
import {EntryService}      from '../Services/entry.service';

@Component({
   selector    : 'app-root',
   templateUrl : './app.component.html',
   styleUrls   : ['./app.component.css']
})

export class AppComponent implements OnInit {
   entries: Entry[];

   constructor(private entryService: EntryService) { }

   ngOnInit(): void {
      this.entryService.getEntries().subscribe(data => {this.entries=data;}, err => {console.log(err);});
   }

} //end of Component

The old working entry.service.ts file in Angular2 is the following:

import { Injectable }           from '@angular/core';
import { Http }                 from '@angular/http';
import { Observable }           from 'rxjs/Observable';
import { Entry }                from '../Classes/entry';
import 'rxjs/add/operator/map';

@Injectable()
export class EntryService {

   constructor(private http: Http) { }

   getEntries(): Observable<Entry[]> {
      return this.http.get('http://192.168.1.3:3000/api/getEntries').map(res => res.json() as Entry[]);
   }

} //end of Service

Now, in Angular 8, .json() function doesn't exist anymore. How can I adjust my code in Angular 8 in order to work??

Generally speaking, is my method of handling http requests a good practice or could it be implemented with a better manner? I don't know Angular in-depth so this is why i'm asking.

Thank you in advance for your time!

Kostas_Me_
  • 83
  • 3
  • 17

2 Answers2

1

Use the HttpClientclass from HttpClientModule if you're using Angular 4.3.x and above:

import { HttpClientModule } from '@angular/common/http';

 imports: [
   BrowserModule,
   HttpClientModule
 ],
 ...

 class MyService() {
    constructor(http: HttpClient) {...}

It's an upgraded version of http from @angular/http module with the following improvements:

  • Interceptors allow middleware logic to be inserted into the pipeline
  • Immutable request/response objects
  • Progress events for both request upload and response download
  • JSON is an assumed default and no longer needs to be explicitly parsed
  • Typed, synchronous response body access, including support for JSON body types

You can read about how it works here.

Also pay attention that old http was injected using Http class token instead of the new HttpClient


@NgModule({
 imports: [
   BrowserModule,
   HttpModule
 ],
 ...

 class MyService() {
    constructor(http: Http) {...}
Shashank
  • 437
  • 2
  • 6
  • 21
0

HttpClient.get() applies res.json() automatically and returns Observable>. You no longer need to call this function yourself.

See Difference between HTTP and HTTPClient in angular 4?

Don't need to use this method:

.map((res: Response) => res.json());
Suhas Parameshwara
  • 1,344
  • 7
  • 15