间隔上的Ionic2或Angular2 http请求
我正在尝试创建一个数据服务,该服务每隔设置的秒数从API中提取数据,并返回API返回的两种不同数据类型的两个可观察值。我是一个新的观察,所以任何帮助将不胜感激 我的API返回两个json对象数组(例如,间隔上的Ionic2或Angular2 http请求,angular,rxjs,observable,ionic2,angular2-http,Angular,Rxjs,Observable,Ionic2,Angular2 Http,我正在尝试创建一个数据服务,该服务每隔设置的秒数从API中提取数据,并返回API返回的两种不同数据类型的两个可观察值。我是一个新的观察,所以任何帮助将不胜感激 我的API返回两个json对象数组(例如,{'Data1':[array of data objects],'Data2':[array of data objects]})。我可以做类似的事情吗 @Injectable() export class DataService { data: any = null; dataType
{'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
}
}
然后在我的组件中,我只需导入数据服务并调用data1=DataService.getData1()
当http请求触发时,该调用是否会在10秒的间隔内继续更新数据?同样地,我对可观测数据还不熟悉,如果这是完全错误的话,我很抱歉。您的方法的一个问题是,当您调用
getData1()
或getData2()
时,无法保证已经收到数据
我也看不到您在哪里调用start()
我认为在
this.http.get(…)…
上调用subscribe(…)
是一个错误flatMap()
自行完成订阅。它期望可观察
而不是订阅
,但当您调用subscribe()
aSubscription
时,您将得到一个订阅。要修复此问题,请将内部的subscribe
替换为do
(并确保导入了do
操作符),或者将代码从subscribe
移动到地图您的服务模块如下所示
@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()));
}
}
当您想取消订阅时,请呼叫stop。尝试时发生了什么?您多次(至少两次)订阅了cold Observable,stop
仅从其中之一取消订阅。
@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();
}
}