在不使用构造函数的情况下注入服务

时间:2019-12-22 20:27:15

标签: angular typescript rxjs

我正在尝试创建一个通用的HTTP服务,该服务可以执行所有基本的HTTP请求。因此,该服务可能如下所示:

export class GenericService {
constructor(
private http: HttpClient
) {
  this.data();
}
data() {
  return this.http.get(`${environment.apiUrl}/..../`)
    .pipe(map(data => {
    return  data;
  }));
 }

} 然后,我想创建一个数据管道,以扩展每个组件。该类可能看起来像这样:

  export class DataPipe implements OnDestroy {
  subscription;
  constructor(private dataSvc: GenericService) {
  }
  getData(source: any) {
  this.subscription = this.dataSvc.data()
    .subscribe(data => {
    source = data;
  });
  } 
  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
 }

最后是一个组件:

    export class Component extends DataPipe {
    source: any;
    constructor() {
     super(GenericService);
   }

   getData(source);
 }

我假设传递给getData()的“源”将获得实际值。即使工作正常,在super(GenericService)也会出现错误;因为GenericService的构造函数需要一个参数。理想情况下,我什至不想在组件中处理GenericService。开发人员只需知道要使用DataPipe类扩展其组件并调用getData()。这样的架构,我什至会朝正确的方向发展吗?

谢谢

2 个答案:

答案 0 :(得分:0)

此方法存在几个问题。首先,是source = data不会为组件中的source设置值,因为:

  

JavaScript参数按值传递:该函数仅到达   知道值,而不是参数的位置。

第二,即使这行得通,您仍需要在组件中执行其他操作才能知道何时 source收到值(因为这是HTTP调用)谁设置的。)

最后,我认为没有理由只为您描述的问题创建基类(这也将迫使您创建mixins以便与其他类一起扩展组件)。但是,如果您真的为此目的extend,则可以创建一个 BaseComponent

export class BaseComponent {
  source: any;

  constructor(public service: MyService) {}

  data() {
    this.service.data().subscribe(data => this.source = data);
  }

}

现在您可以扩展到 BaseComponent ,为其构造函数提供服务,调用super并调用data()this.source将在子组件中获得一个值, API调用成功后。

答案 1 :(得分:0)

我想通知你。

  1. HttpClient是整个项目中的singleton服务,如果您在HttpClientModule中导入了app.module.ts

  2. HttpClient发出的
  3. 请求,在收到服务器的结果后,它们将自动关闭。

我建议您仅从需要从服务器获取必要数据的组件中导入服务并调用该函数(它将向服务器发送请求)

这是简单的例子。

https://stackblitz.com/edit/call-http-request-in-angular-6-cwrdrr?file=src/app/app.component.ts