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

时间:2018-08-13 20:55:40

标签: angular http angular6

我试图在角度6中创建一个service-1。service-2将使用service-1来进行http请求。

服务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()需要一个参数。

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

服务1

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需要一些参数。我不知道有关该论点的细节。

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

1 个答案:

答案 0 :(得分:1)

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

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

      }
    }

然后您可以通过访问“ this.myService”在班级中使用此注入的服务