代码之家  ›  专栏  ›  技术社区  ›  Mateusz Byczkowski

角度4:将http转换为httpclient,config

  •  1
  • Mateusz Byczkowski  · 技术社区  · 7 年前

    我有以下角度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 是的。

    谢谢你的帮助

    1 回复  |  直到 7 年前
        1
  •  1
  •   Akj    7 年前

    尝试基本方法:

    进口 HttpClientModule 并将其添加到app.module.ts中 imports[]

    import { HttpClientModule } from '@angular/common/http';
    
    @NgModule({
      imports: [
        BrowserModule,
        // import HttpClientModule after BrowserModule.
        HttpClientModule,
      ],
      declarations: [
        AppComponent,
      ],
      bootstrap: [ AppComponent ]
    })
    export class AppModule {}
    

    应用服务.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)
    })