我目前有一个combineLatest
方法,我通过我的课程提供这个方法:
export class ObservableDataSource extends DataSource<any> {
private value: any[];
private key: string;
constructor(value: any[], key) {
super();
this.value = value;
this.key = key;
}
connect() {
//Code related to question starts here
return combineLatest(this.value, (data) => {
return data[this.key];
});
//Code related to question ends here
}
disconnect() {}
}
在我的单元测试中,我有一个beforeEach,我用来实例化组件并提供一个observable:
const dummyData = [{
visible: {
data: 'test123'
}
}];
const observableDummyData = Observable.of([dummyData]);
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{provide: ObservableDataSource, useValue: new ObservableDataSource(observableDummyData, 'visible')}
]
});
});
it('should be created', inject([ObservableDataSource], (service: ObservableDataSource) => {
expect(service).toBeTruthy();
}));
唯一的问题是,在查看控制台以获取karma运行程序时,此this.value显示为可观察对象,从combineLatest中发出的数据显示为空TypeError: Cannot read property 'visible' of undefined
。可能的原因:
Observable.of
任何建议,都非常感谢。谢谢。
答案 0 :(得分:2)
我认为您的代码中存在多个问题。
<强> 1 强>
您的服务期望其value
参数是一个数组,但您提供的是一个简单的Observable。
<强> 2 强>
combineLatest
使用多个可观察参数,而不是参数数组。
return combineLatest(obsA, obsB, obsC, (a, b, c) => { ... });
// or with the spreading operator
return combineLatest(...arrayOfObs).map((...data) => { ... });
const dummyData1 = [{
visible: {
data: 'test123'
}
}];
const dummyData2 = [{
visible: {
data: 'somethingElse'
}
}];
const observableDummyData = [
Observable.of(dummyData1),
Observable.of(dummyData2),
];
请参阅documentation for spreading operator
connect() {
return combineLatest(...this.value).pipe(
map(...data) => {
return data[this.key]
}
);
}