代码之家  ›  专栏  ›  技术社区  ›  Rob Monhemius

如何在另一个服务中创建依赖HttpService的类的实例?

  •  -1
  • Rob Monhemius  · 技术社区  · 6 年前

    服务-1

    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    
    @Injectable({
      providedIn: 'root'
    })
    export class HttpService {
      constructor(
          private http: HttpClient
      ) {
         // do something with http
      }
    }
    

    服务2

    import { Injectable } from '@angular/core';
    import{ HttpService } from './user-account/http.service'
    
    @Injectable({
      providedIn: 'root'
    })
    export class ServiceTwo{
      http: HttpService;
      constructor() {
         this.http = new HttpService() ;
      }
    }
    

    这不管用,因为 this.httpService = new HttpService()

    所以我尝试了另一种方法:

    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    
    @Injectable({
      providedIn: 'root'
    })
    export class HttpService {
      http: HttpClient;
      constructor() {
         this.http = new HttpClient();
      }
    }
    

    服务2

    import { Injectable } from '@angular/core';
    import{ HttpService } from './user-account/http.service'
    
    @Injectable({
      providedIn: 'root'
    })
    export class ServiceTwo{
      http: HttpService;
      constructor() {
         this.http = new HttpService() ;
         // do something with http
      }
    }
    

    这不起作用,因为 HttpService 需要一些论证。我不知道这场争论的细节。

    1 回复  |  直到 6 年前
        1
  •  1
  •   abdullahkady    6 年前

    在您自己的服务中使用依赖注入,就像您将HttpClient注入到service-1中一样,您将按如下方式将service-1注入到service-2的构造函数中:

        export class ServiceTwo{
          constructor(private myService: ServiceOne) {
    
          }
        }