简体   繁体   中英

Angular 2 to latest - jsonp and URLSearchParams to HttpClient and HttpParams

I am trying to upgrade this to latest but getting error to display the data. i need to refactor from Jsonp to HttpClient, and HttpParams for below code. Any help would be great.

import { Injectable } from '@angular/core';
import {Jsonp, URLSearchParams} from '@angular/http';
import 'rxjs/Rx';

@Injectable()
export class MyService {
    apikey: string;

    constructor(private _jsonp: Jsonp) {
        this.apikey = 'my_api_key';
        console.log('it works');
    }

    getData() {
        var search = new URLSearchParams();
        search.set('sort_by','popularity.desc');
        search.set('api_key', this.apikey);
        return this._jsonp.get('url', {search})
          .map(res => {
            return res.json();
          })
    }
}

This should be able to fix your problem. Please check doc for more info

In you module

import { NgModule }         from '@angular/core';
import { BrowserModule }    from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';

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

In your service

import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class MyService {
    apikey: string;

    constructor(private http: HttpClient){
        this.apikey = 'my_api_key';
    }

    getData(): Observable<any>  {
        const params = new HttpParams()
            .set('sort_by', popularity.desc)
            .set('api_key', this.apikey);
        return this.http.get('url', {params});
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM