Observable Not Emitting Data on Ionic View App


#1

I use the subscribe function to get data from a JSON file and format it as an ion-menu. This works fine when I test with ionic -serve but when I upload and test with the Ionic View app nothing shows up in the menu. This is how I get the data:

ngOnInit() {
  this.getData().subscribe(data => { this.menu_labels = data; console.log("menu_labels",this.menu_labels);
  alert("menu_labels.title " + this.menu_labels[0].title ); 
  });
}
getData() {
  return this.http.get('../assets/main-menu.json').map(res=> res.json().pages);
}

I know the Observable never resolves becasue the “alert(…)” statement inside of subscribe never shows. I also use *ngIf in my ion-list markup to make sure menu_labels is not undefined. Does anyone know of an issue that would cause this? Thanks.


#2

It’s often something simple, like the wrong file path. I’ve convinced myself many times that a problem is hard because Observables are complicated – and they are – but the problem has a simple solution. Can you put a do on your http.get, to see what its raw data is? That’s what I’d check first.


#3

Can you put a do on your http.get

Can you explain what you mean by this?

The http.get request returns data when I test in browser. It is only when I use the Ionic View app that no data is returned. I just tried removing the “…” from “…/assets/main-menu.json” but does not change the result–app does not display content but browser displays all content just fine.


#4

With rxjs Observables, there’s a do operator, often used in debugging.

this.someObservable.do(value => console.log(value));

You stick the do in between other operators, to track values emitted by the Observable.
Edit: If it changes only in Ionic View, maybe Ionic View is storing images somewhere different.


#5

I keep getting a compiler error “Property ‘do’ does not exist on type ‘Observable’”.

I did, however, add an alert to catch an error from .subscribe() which output “Response with status: 0 for URL: null”.


#6

If you are using rxjs for your Observables, then you can import do with

import 'rxjs/add/operator/do';

in app.component.ts.


#7

As mentioned before, the right path is
this.http.get('./assets/main-menu.json')

by the way, you could have used an error handler in the subscribe to catch errors.

this.getData().subscribe(data => {
  this.menu_labels = data;
  console.log("menu_labels",this.menu_labels);
  alert("menu_labels.title " + this.menu_labels[0].title ); 
}, err => {
  console.error(err);
});

with this error handler, you can see what have gone wrong.


#8

Yes, I realized that and added the error handler which returned “Response with status: 0 for URL: null”. From my research I believe this is a CORS issue, but I am confused because it is a local file that I am performing the http request on so it shouldn’t be cross-origin. I also corrected my file path. Any idea where to go from here?