Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import {Injectable} from '@angular/core';
- import {Http, XHRBackend, RequestOptions, Request, RequestOptionsArgs, Response, Headers} from '@angular/http';
- import {Observable} from 'rxjs/Observable';
- import 'rxjs/add/operator/map';
- import 'rxjs/add/operator/catch';
- import {Subject} from 'rxjs/Subject';
- @Injectable()
- export class customHttp extends Http {
- tokenexpired: Subject<boolean> = new Subject<boolean>();
- constructor(backend: XHRBackend, options: RequestOptions) {
- super(backend, options);
- console.log('In constructor');
- let token = localStorage.getItem('auth_token'); // your custom token getter function here
- options.headers.set('Authorization', `Bearer ${token}`);
- this.tokenexpired.next(false);
- console.log('token is');
- console.log(this.tokenexpired);
- }
- request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
- console.log('In service');
- let token = localStorage.getItem('auth_token');
- if (typeof url === 'string') { // meaning we have to add the token to the options, not in url
- if (!options) {
- // let's make option object
- options = {headers: new Headers()};
- }
- options.headers.set('Authorization', `Bearer ${token}`);
- } else {
- // we have to add the token to the url object
- url.headers.set('Authorization', `Bearer ${token}`);
- }
- return super.request(url, options).catch(this.catchAuthError(this));
- }
- post(url: string, body: any, options?: RequestOptionsArgs): Observable<any> {
- console.log('Before the request...');
- return super.post(url, body, options)
- .catch((err: any): any => {
- if (err.status === 400 || err.status === 422) {
- //FIRE NOTIFICATION IN THIS POINT FOR EXAMPLE.
- return Observable.throw(err);
- } else {
- }
- })
- .finally(() => {
- console.log('After the request...');
- });
- }
- private catchAuthError(self: customHttp) {
- // we have to pass HttpService's own instance here as `self`
- return (res: Response) => {
- console.log(res);
- if (res.status === 401 || res.status === 403) {
- // if not authenticated
- console.log(res);
- this.deletetoken();
- }
- return Observable.throw(res);
- };
- }
- private deletetoken() {
- localStorage.removeItem('token');
- this.tokenexpired.next(true);
- }
- }
- constructor(private http: customHttp) {
- this.number = this.generate();
- }
- register(data: any): Promise<Response> {
- let datatosend = JSON.stringify({
- email: data.email,
- password: '12345',
- user: {cnic: data.cnic, phone: this.number}
- });
- return this.http
- .post(authUrls.register,datatosend , {headers: this.headers})
- .toPromise()
- .then(response => {
- this._profileChange(response);
- this._serrviceLogin();
- return response;
- })
- .catch(this.handleError);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement