Last active
November 1, 2022 02:48
-
-
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/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
}); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Simple