我正在努力解决Angular 8应用程序中的异步数据访问模式(来自.NET(。我正在使用组件、用于数据访问的服务以及处理服务中的数据的自定义类。似乎我应该将数据访问服务注入到我的组件中 - 但是我在哪里利用我的自定义类来实现业务逻辑?
我想要什么:
元件:
import { Component, OnInit } from '@angular/core';
import { SampleService } from '../services/sample.service';
import { CustomBusinessLogic } from '../../cbl';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.scss']
})
export class Example implements OnInit {
constructor(private sampleService: SampleService) { }
ngOnInit() { }
doSomething() {
const dataToActOn = this.sampleService.getDataToActOn();
// Do something with dataToActOn here
const p = new CustomBusinessLogic.Calculator(
dataToActOn.params as Settings,
dataToActOn.data1,
dataToActOn.data2
);
const res = p.calculate();
}
}
服务:
import { Injectable } from '@angular/core';
import { ExampleDataService } from './data/example-data.service';
import { SettingsService } from './data/settings.service';
import { forkJoin } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class SampleService {
data1: any[];
data2: any[];
params: [];
constructor(private projections: ,
private data: ExampleDataService, private settingsService: SettingsService) { }
loadDataHttp() {
const id = 'for-testing';
const b = this.data.getDataSet1(new Date());
const p = this.data.getDataSet2(new Date());
const m = this.settingsService.getDataSet3(id, 2018);
return forkJoin([b, p, m]);
}
getDataToActOn() {
this.loadDataHttp().subscribe(data => {
this.data1 = data[0];
this.data2 = data[1];
this.params = data[2];
// HOW DO I RETURN THIS DATA TO THE COMPONENT
// AND HAVE IT AVAILABLE TO MY CUSTOM BUSINESS LOGIC??
});
}
}
我的问题(在此伪/示例代码中(是当我的组件到达new CustomBusinessLogic.Calculator
时,尚未从服务返回任何数据。
如何重构它,以便我可以对从我的组件或其他服务中的服务返回的数据进行操作?
谢谢!
更改以下内容:
getDataToActOn() {
this.loadDataHttp().subscribe(data => {
this.data1 = data[0];
this.data2 = data[1];
this.params = data[2];
// What now?
});
}
为此,请在服务中:
getDataToActOn() {
return this.loadDataHttp();
}
还要更改此设置:
doSomething() {
const dataToActOn = this.sampleService.getDataToActOn();
// Do something with dataToActOn here
const p = new CustomBusinessLogic.Calculator(
dataToActOn.params as Settings,
dataToActOn.data1,
dataToActOn.data2
);
const res = p.calculate();
}
为此,在组件中:
doSomething() {
this.sampleService.getDataToActOn().subscribe(
(dataToActOn) => {
const p = new CustomBusinessLogic.Calculator(
dataToActOn.params as Settings,
dataToActOn.data1,
dataToActOn.data2
);
const res = p.calculate();
}
);
}
抱歉,如果格式有点搞砸。
getDataToActOn现在显然有点薄。通常,您将使用该方法将参数、选项和标头传递给 http 服务。
您应该在服务getDataToActOn
函数中返回Observable
。
所以函数应该像下面这样。
getDataToActOn() {
return this.loadDataHttp().pipe(map(data => ({
data1: data[0],
data2: data[1],
params: data[2]
})));
}
如果您想深入研究 RxJSpipe
和map
,请查看此处。
然后订阅组件中的数据
this.sampleService.getDataToActOn().subscribe(dataToActOn => {
const p = new CustomBusinessLogic.Calculator(
dataToActOn.params as Settings,
dataToActOn.data1,
dataToActOn.data2
);
const res = p.calculate();
});