首页 > 解决方案 > 如何创建依赖于另一个服务中的 HttpService 的类的实例?

问题描述

我正在尝试在 Angular 6 中创建一个 service-1。这个 service-1 将被 service-2 用来发出 http-requests。

服务-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 的类的实例?

标签: angularhttpangular6

解决方案


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

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

      }
    }

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


推荐阅读