angular - 如何创建依赖于另一个服务中的 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 的类的实例?
解决方案
在您自己的服务中使用依赖注入,就像您将 HttpClient 注入到 service-1 中一样,您将 service-1 注入到 service-2 的构造函数中,如下所示:
export class ServiceTwo{
constructor(private myService: ServiceOne) {
}
}
然后,您可以通过访问“this.myService”在您的课程中使用此注入服务
推荐阅读
- html - 使用 webpack 缓存的 index.html
- ios - 如何在初始化过程中用另一个属性初始化一个属性 - SwiftUI
- github - 非 jekyll github 页面站点的一个链接不起作用。是否有任何我需要删除的缓存(非本地)?
- c++ - 使用 C++ 的双变量 Gurobi
- jboss - 来自 ActiveMQ Artemis 主题的消息不会传递到所有订阅的 MDB
- php - MYSQL / PHP - 如何检查第二个查询以检查复选框
- quarkus - Quarkus:如何与 Artemis 使用点对点消息传递?
- r - 我可以根据同一 tibble 中另一列的值过滤一列吗?
- c# - 替换正则表达式匹配
- javascript - 从字符串 JavaScript 创建嵌套对象