Skip to content

Instantly share code, notes, and snippets.

@levymetal
Last active November 1, 2022 02:48
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save levymetal/b428cb12541393491f929ba0515bf34e to your computer and use it in GitHub Desktop.
Save levymetal/b428cb12541393491f929ba0515bf34e to your computer and use it in GitHub Desktop.
Example of using observable from within a Service on Ionic 2. Full blog post here: http://christianvarga.com/how-to-create-and-monitor-observables-in-ionic-2-service/
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
@Injectable()
export class ApiService {
private errorObserver: any;
public error: any;
constructor(public http: Http) {
this.errorObserver = null;
this.error = Observable.create(observer => {
this.errorObserver = observer;
});
}
get(url) {
let headers = new Headers({
'X-API-KEY' : 'my-api-key',
'Content-Type': 'application/json; charset=utf-8'
});
let options = new RequestOptions({ headers: headers });
return this.http.get(url, options)
.map(res => res.json())
.catch(error => this.handleError(error));
}
private handleError(error) {
this.errorObserver.next(error);
return Observable.throw(error.json().error || 'Server error');
}
}
import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { ApiService } from '../providers/api-service';
@Component({
template: `<ion-nav [root]="rootPage"></ion-nav>`
})
export class MyApp {
...
constructor(platform: Platform, private apiService: ApiService) {
platform.ready().then(() => {
...
this.apiService.error.subscribe((error) => {
if (error.status == 403) {
// unauthorised, redirect to login
}
// error, alert message
});
});
}
}
@risingagain
Copy link

Simple

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment