gpt4 book ai didi

javascript - Angular 2 到最新版本 - jsonp 和 URLSearchParams 到 HttpClient 和 HttpParams

转载 作者:行者123 更新时间:2023-11-30 13:55:10 24 4
gpt4 key购买 nike

我正在尝试将其升级到最新版本,但显示数据时出错。我需要将 Jsonp 重构为 HttpClient,并为以下代码重构 HttpParams。任何帮助都会很棒。

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();
})
}
}

最佳答案

这应该能够解决您的问题。请查看doc了解更多信息

在你的模块中

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 {}

为您服务

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});
}
}

关于javascript - Angular 2 到最新版本 - jsonp 和 URLSearchParams 到 HttpClient 和 HttpParams,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57437421/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com