A
A
asd dsa2018-11-20 13:44:29
JavaScript
asd dsa, 2018-11-20 13:44:29

How to rewrite Http to HttpClient?

Migrating from angular2 to angular7, tell me how to rewrite module Http requests to HttpClient ?

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/throw';

export class ExpenseService {
   jwtToken: string;
    constructor(private http: Http) {
        const theUser:any = JSON.parse(localStorage.getItem('currentUser'));
        if (theUser) {
            this.jwtToken = theUser.token;
        }
    }
    
    saveExpense(userid, oExpense){
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');
        headers.append('Authorization', `${this.jwtToken}`);
        let options = new RequestOptions({ headers: headers });
        return this.http.post(`http://localhost:1978/api/expense/${userid}`, JSON.stringify(oExpense), options)
            .map((response: Response) => response.json())
            .catch(this.handleError);
    }

    getExpenses(userid, oExpense) {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');
        headers.append('Authorization', `${this.jwtToken}`);
        let options = new RequestOptions({ headers: headers });

        return this.http.post(`http://localhost:1978/api/expense/report/${userid}`, JSON.stringify(oExpense), options)
            .map((response: Response) => response.json())
            .catch(this.handleError);
    }

    getExpenseTotal(userid, oExpense) {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');
        headers.append('Authorization', `${this.jwtToken}`);
        let options = new RequestOptions({ headers: headers });

        return this.http.post(`http://localhost:1978/api/expense/total/${userid}`, JSON.stringify(oExpense), options)
            .map((response: Response) => response.json())
            .catch(this.handleError);
    }

    getExpense(expid) {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');
        headers.append('Authorization', `${this.jwtToken}`);
        let options = new RequestOptions({ headers: headers });

        return this.http.get(`http://localhost:1978/api/expense/${expid}`, options)
            .map((response: Response) => response.json())
            .catch(this.handleError);
    }

    delExpense(expid) {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');
        headers.append('Authorization', `${this.jwtToken}`);
        let options = new RequestOptions({ headers: headers });

        return this.http.delete(`http://localhost:1978/api/expense/${expid}`, options)
            .map((response: Response) => response.json())
            .catch(this.handleError);
    }

     private handleError(error: Response) {
        console.error(error);
        return Observable.throw(error.json().error || 'Server error');
    }
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
spnq, 2018-11-20
@yaNastia

In general, it's best to take these requests to the service and import HttpClient there. Next, we inject it into the service constructor: After that, we make the necessary method for the request (in this example, let it return an Observable with an array of any data):

getServices(): Observable<Array<any>> {
    return this.http.get<Array<any>>(`адрес реста`, {headers:{ 'Content-Type':'application/json' , и так далее}});
  }

An object with headers is generally optional and there are several options for how to add them, but this one fits your example.
Then you import your service into the component and inject it into the constructor of this component:
Next, in the necessary hook, for example, in ngOnInit() you call the method and subscribe:
ngOnInit() {
    this.service.getServices().subscribe( next => ну и дальше все, как обычно);
}

D
Dmitry Eremin, 2018-11-20
@EreminD

well, the simplest - in the constructor
constructor(private http: Http) we change to constructor(private http :
HttpClient )

M
msdosx86, 2018-11-30
@msdosx86

1) rename Http to HttpClient (from angular/core, sometimes it can be imported from selenium by accident)
2) import imports: [ HttpClientModule ] in the root module
3) remove all response.json() from all methods, as it automatically does HttpClient

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question