Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将Indexeddb作为离线数据存储的Angular5 HTTP服务:如何处理Observable<;回应>;vs对象_Angular_Http_Indexeddb_Angular2 Observables - Fatal编程技术网

将Indexeddb作为离线数据存储的Angular5 HTTP服务:如何处理Observable<;回应>;vs对象

将Indexeddb作为离线数据存储的Angular5 HTTP服务:如何处理Observable<;回应>;vs对象,angular,http,indexeddb,angular2-observables,Angular,Http,Indexeddb,Angular2 Observables,我有一个Angular 5应用程序,在数据库中存储数据,我通过如下服务调用获取数据: this.dataSvc .getSomeData() .map(response => response.json()) .subscribe( data => { this.someVariable = data } ) 服务基本上是这样的: public getSomeData(): Observable<Response> {

我有一个Angular 5应用程序,在数据库中存储数据,我通过如下服务调用获取数据:

this.dataSvc
    .getSomeData()
    .map(response => response.json())
    .subscribe(
      data => { this.someVariable = data }
    )
服务基本上是这样的:

 public getSomeData(): Observable<Response> {
      return this.http.get(SERVER_URL);
 }
问题是“return Observable.of(data)”不正确,在组件端,网络返回得到一个响应,它可以将响应映射到json等,但indexeddb调用返回一个无法映射到json的对象,因为它已经是一个javascript对象

我想在服务级别处理在线/离线情况-我知道我可以在组件中这样做,在有网络时调用在线服务并使用可观察的形式,在没有网络时调用离线服务并接收javascript对象,但其中一些服务在许多组件中使用,我希望集中处理在线/离线情况的代码,而不是在每个组件中复制这些代码

问题是如何处理从indexeddb存储中获取的对象的返回,以便以期望HTTP响应的代码能够正确处理的方式对其进行格式化


或者,有没有其他/更好的方法来解决隐藏在我盲点中的这个问题?

不要订阅
getRecord()
调用。相反,请返回:

返回这个.idbService.getRecord('idbStore');
根据您的评论,您需要:

if(this.networkStatus==“脱机”)
{
返回这个.idbService.getRecord('idbStore');
}否则{
返回此.http.get(服务器URL)
.map(response=>response.json());
}
将另一部分更改为:

this.dataSvc
.getSomeData()
.订阅(数据=>{
this.someVariable=数据;
});

抛出一个错误'TypeError:response.json不是一个函数',您需要将
.map(response=>response.json())
移动到该代码的
部分,否则
部分就行了,它确实需要对使用该服务的所有组件进行一些代码更改,这是我希望避免的,但肯定是可以管理的。
 if (this.networkStatus == 'Offline') {
      this.idbService.getRecord('idbStore')
      .subscribe(data => {
           console.log("Idb Data: ",data);
           return Observable.of(data);
      }
 } else {
      return this.http.get(SERVER_URL);
 }