Publish event from handle error function in rest provider


#1

Hello,

I hope we could help me. I’am a beginner with ionic framework.
I have an app with a restfull api server side. I make a rest provider client to interact with this api :

In this provider i have a function to handle error in each request. When the status code is 401 i would like to publish an event “session:expired” to catch it in my app.component.ts to redirect user to login page.

For example a sample of my code :

@Injectable()
export class RestProvider {
.......
myApiUrl = https://......

  constructor(public http: HttpClient,
              public loadingCtrl: LoadingController,
              public loader: LoaderProvider,
              public events: Events) {

  }
/***
   * API REST FOR USER WEBSERVICE
   */  
  getUsers(params=null): Observable<Student[]> {            
    return this.http.get(this.myApiUrl + "/users", { params: params, headers:this.customHeader })
                    .map(this.extractData)                    
                    .catch(this.handleError);                
  }

...........


private handleError (error: Response | any) {
  ......

    if(error.status == 401)
    {
      console.log("Status Error 401 : " + error.status);
      this.events.publish('session:expired');
   }

    return ......
  }

My problem : the “this.event.publish” in the handleError(or extractData) function doesn’t work and break/freeze my App with no error in console ??

if i publish an event in the getUsers function that’s work(but no interest) :

  getUsers(params=null): Observable<Student[]> {         

    this.events.publish('session:expired');
    return this.http.get(this.myApiUrl + "/users", { params: params, headers:this.customHeader })
                    .map(this.extractData)                    
                    .catch(this.handleError);                
  }

Is it possible to publish event in map or catch function of http object ? maybe i have not the “good practice” ?

Thanks you in advance and sorry for my english :confused: