Angular 4:Http转HttpClient,配置
Angular 4: Converting Http to HttpClient, config
我在 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();
}
我想将它重写为 HttpClient 而不是 Http,所以我修改了注入构造函数的 http 类型,但我不知道(也找不到)如何处理 config?: RequestOptionsArgs
.
感谢帮助
尝试基本方法:
导入HttpClientModule
并将其添加到imports[]
中的app.module.ts
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
// import HttpClientModule after BrowserModule.
HttpClientModule,
],
declarations: [
AppComponent,
],
bootstrap: [ AppComponent ]
})
export class AppModule {}
app.service.ts
在组件
中导入HttpClient
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)
})
我在 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();
}
我想将它重写为 HttpClient 而不是 Http,所以我修改了注入构造函数的 http 类型,但我不知道(也找不到)如何处理 config?: RequestOptionsArgs
.
感谢帮助
尝试基本方法:
导入HttpClientModule
并将其添加到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
在组件
中导入HttpClient
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)
})