Mateusz Byczkowski
Mateusz Byczkowski

Reputation: 326

Angular 4: Converting Http to HttpClient, config

I have the following code in Angular 4:

constructor(private baseUrl: string, private http: Http) {}

get(url: string, config?: RequestOptionsArgs): Promise<any> {
    return this.http.get(this.prependBaseUrl(url), config)
        .toPromise();
}

I would like to rewrite it to HttpClient instead of Http, so i modified type of http injecting to constructor, but i don't know (and can't find anywhere) what to do with config?: RequestOptionsArgs.

Thanks for help

Upvotes: 1

Views: 212

Answers (1)

Akj
Akj

Reputation: 7231

Try Basic Approach:

import HttpClientModule and add it into app.module.ts in imports[]

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

@NgModule({
  imports: [
    BrowserModule,
    // import HttpClientModule after BrowserModule.
    HttpClientModule,
  ],
  declarations: [
    AppComponent,
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}

app.service.ts

import HttpClient in component

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable()
export class AppService{
  constructor(private http: HttpClient) { }
getData(): Observable<any>{

    return this.httpClient.get('request_url',RequestOptionsArgs)
    }
}

app.component.ts:

import {AppService} from './app.service.ts';

constructor(private appservice: AppService){
  this.appservice.getData().subscribe(response => {
  console.log(response)
})

Upvotes: 1

Related Questions