我有2-5个服务,它们执行相同的代码,但是每个服务具有不同的API调用,并且我需要所有页面中的数据,因此第一个将订阅将获取数据,第二个将仅获取数据。订阅(带有标志的简单解决方案)
例如,其中一个调用从服务器获取配置,第二个调用获取设置列表,用户列表... etc
我想以一种不错的方式来抽象它,例如资源加载器或资源工厂,而无需扩展父类或抽象类
我的服务代码之一如下:
export class data1Service {
private static readonly apiEndpoint: string ='get_data1';
get$: Observable<Setting>;
setting: data1 = new data1();
private flag = false;
private data1Subject = new AsyncSubject<data1>();
private logger: Logger;
constructor(private readonly http: HttpClient, logger: Logger) {
this.data1get$ = this.data1Subject.asObservable();
}
loaddata1() {
if (this.flag) {
return;
}
this.flag = true;
return this.http.get<data1>(data1Service.apiEndpoint).subscribe(
async data => {
const data1Obj = plainToClass(data1, data as Object);
const validationResult = await validate(data1Obj);
if (validationResult.length > 0) {
this.data1 = new data1();
} else {
this.data1 = data1Obj;
this.logger.debug('validation succeed');
}
this.data1Subject.next(this.data1);
this.data1Subject.complete();
},
(err: any) => {
this.logger.debug('could not fetch data1');
this.data1Subject.next(this.data1);
this.data1Subject.complete();
}
);
}