多个组件中的相同代码 Angular 6.



我有几个组件在做同样的工作。 每个人只使用不同的参数进行相同的 API 调用:

this.http.get('url' + parameter).subscribe((data: Array<any>) => {
//some state dispatches and other stuff
return response;
});

出于某种原因,我不想在每个组件中编写相同的代码。例如,在Java中,我在这种情况下使用超类。在Angular中,大多数时候服务就足够了。但不是在这种情况下。

我尝试编写一个新类:

export class Content {
constructor(private http: HttpClient) { }
getContent() {
this.http.get('url' + parameter).subscribe((data: Array<any>) => {
//some state dispatches and other stuff
return response;
});      
}
}

现在我可以在每个组件中初始化这个类,它可以工作:

export class MyComponent {
constructor(private http: HttpClient) { }
toggle() {
new Content(http);
}
}

问题是我必须使用我注入HttpClient的构造函数。我不希望这样,因为我必须传递其他依赖项(与问题无关(。

那么这是最佳实践吗,如果是,我如何在不传递的情况下使用HttpClient

  • 在将结果返回到组件之前,应在服务中使用map来执行常见处理。
  • 服务应向调用组件返回一个可观察量。然后,组件可以从该点进一步处理结果。
  • 这可能只是为了示例,但不要使用any如果可以帮助,请定义一个接口并使用它来定义响应和返回类型。这为您的代码增加了类型安全性,这是创建打字稿的主要原因之一。
  • 您应该将服务注入到组件中。实际上,您应该始终对任何依赖项使用注入。如果要执行不同的操作,请创建不同的方法来在服务中处理它们,或创建采用参数的方法。根据我的经验,没有理由手动创建HttpClient实例。

以下是我认为您正在问的非常常见的方法。

import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class ContentService {
constructor(private http: HttpClient) { }
getContent() : Observable<Array<any>> {
return this.http.get<Array<any>>('url' + parameter).pipe(map((data: Array<any>) => {
// common processing here
return data;
}));
}
}
@Component({})  
export class MyComponent {
constructor(private contentService: ContentService) { }
data: Array<any> = [];
toggle() {
this.contentService.getContent().subscribe(data => {
// do something with returned data like...
this.data = data;
});
}
}

只需在创建服务的类之前放置@Injectable,然后您就可以将服务注入 app.module.ts 的提供程序中

@Injectable()
export class Service {
constructor(
private http: HttpClient,
) {}
getContent() {
this.http.get('url' + parameter).subscribe((data: Array<any>) => {
//some state dispatches and other stuff
});      
}
}

然后,您可以在导入服务的其他组件的构造函数中使用它:)

constructor(private service: Service) { }

创建一个Service。在您需要的任何组件中导入服务,并在服务中导入 HttpClient。

以下是文档。

使用httpClient创建服务。 使用返回promise的函数。 在此函数中使用 HTTP 请求。 在你的组件中,只需获取服务的实例并在 promise 返回值后执行您想要的任何内容

服务.ts

export class ContentService {
constructor(private http: HttpClient) { }
getContent(): Promise<any> {
this.http.get('url' + parameter).subscribe((data: Array<any>) => {
return new Promise(resolve => resolve('whatever'));
});      
}
}

组件.ts

constrctor (private classService: ClassService) {
classService.getContent()
.then(data => 'do whatever you want with tha data');
}

最新更新