我正在尝试创建一个数据服务,该数据服务每隔设置的秒数从我的API中提取数据,并返回API返回的两种不同数据类型的两个Observable。我是Observables的新手,因此将非常感谢您的帮助。
我的API返回了两个json对象数组(例如{'Data1':[array of data objects], 'Data2':[array of data objects]}
)。我可以做类似的事情吗?
@Injectable()
export class DataService {
data: any = null;
dataType1: DataType1Model[] = [];
dataType2: DataType2Model[] = [];
service: Observable;
constructor(public http: Http) {}
start() {
this.service = Observable.interval(10000)
.flatMap(() => {
this.http.get('url')
.map(res => res.json())
.subscribe(data => {
this.data = data;
this.processData1(this.data.Data1);
this.processData2(this.data.Data2);
});
})
.subscribe()
}
stop(){
this.service.unsubscribe()
}
getData1() {
return this.dataType1
}
getData2() {
return this.dataType2
}
}
然后,在我的组件中,我可以导入DataService并调用data1 = DataService.getData1()
?
http请求触发时,该调用是否会在10秒的时间间隔内继续更新数据,是可以观察到的?同样,我对可观察对象是陌生的,如果这是完全错误的,那么对不起。
您的服务模块将是这样的
@Injectable()
export class DataService {
constructor(private http : Http) { }
// Uses http.get() to load a single JSON file
getData() : Observable<DataType1Model[]> {
return Observable.interval(10000)
.flatMap(this.http.get('url')
.map((res:Response) => res.json()));
}
}
而且您的组件应该像这样-
@Component({
selector: 'Selector',
template: "Template",
providers:[
DataService,
]
})
export class DataComponent implements OnInit{
dataItem: DataType1Model[] ;
constructor(private _itemData:DataService ) { }
getData(){
this._itemData.getData()
.subscribe(
// the first argument is a function which runs on success
(data:DataType1Model[]) => {
this.dataItem = data;
},
// the second argument is a function which runs on error
err => console.error(err),
// the third argument is a function which runs on completion
() => console.log('done loading data')
);
}
ngOnInit() {
console.log('hello `Item` component');
this.getData();
}
stop(){
_itemData.getData()
.unsubscribe();
}
}
想要退订时,请拨打停止电话。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句