Add Service in Custom HTTP service Angular 2 -


i using http interceptor extending http service. needed catch request , fire logout event if user token expired.

the logout service defined in authservice uses http service.

whenever try create instance of authservice , access functions, return undefined.

is there missing?

http.interceptor.ts

import { injectable, ondestroy } "@angular/core"; import { router } '@angular/router'; import { connectionbackend, requestoptions, request, requestoptionsargs, response, http, headers} "@angular/http"; import { observable } "rxjs/rx"; import { environment } "../environments/environment"; import { authservice } './services/auth.service'; import { sharedservice } './services/shared.service'; import { loaderservice } './factory/loader.service';  import 'rxjs/add/operator/map';  @injectable() export class interceptedhttp extends http {     private _router: router;     private _auth: authservice;      constructor(backend: connectionbackend, defaultoptions: requestoptions, private loaderservice: loaderservice) {         super(backend, defaultoptions);     }      request(url: string | request, options?: requestoptionsargs): observable<response> {         return super.request(url, options);     }      get(url: string, options?: requestoptionsargs): observable<response> {         this.showloader();         url = this.updateurl(url);         return super.get(url, this.getrequestoptionargs(options))             .do((res:response) => {                 console.log(res.json());                 let data = res.json();                 if(!data.status && (data.message == "token has expired" || data.message == "token invalid")){                     this._auth.logout();                 }                 /*else if(!data.status && data.message == "some error has occured") {                  }*/             })             .finally(() => {                 this.onend();             });     }      post(url: string, body: string, options?: requestoptionsargs): observable<response> {         this.showloader();         url = this.updateurl(url);         return super.post(url, body, this.getrequestoptionargs(options))                 .do((res:response) => {                     console.log(res.json());                     let data = res.json();                     if(!data.status && (data.message == "token has expired" || data.message == "token invalid")){                         console.log('logged out while request');                         this._auth.logout();                     }                     /*else if(!data.status && data.message == "some error has occured") {                      }*/                 })                 .finally(() => {                     this.onend();                 });     }      put(url: string, body: string, options?: requestoptionsargs): observable<response> {         url = this.updateurl(url);         return super.put(url, body, this.getrequestoptionargs(options));     }      delete(url: string, options?: requestoptionsargs): observable<response> {         url = this.updateurl(url);         return super.delete(url, this.getrequestoptionargs(options));     }      private updateurl(req: string) {         return  environment.api_url + req;     }      private getrequestoptionargs(options?: requestoptionsargs) : requestoptionsargs {         if (options == null) {             options = new requestoptions();         }         if (options.headers == null) {             options.headers = new headers();         }          options.headers.append('accept','application/json');         options.headers.append('content-type', 'application/json');         options.headers.append('device-id','123434234');         options.headers.append('device-type','web');         options.headers.append('authorization','bearer '+window.localstorage['key']);          return options;     }      private onend(): void {         this.hideloader();     }      private showloader(): void {         this.loaderservice.show();     }     private hideloader(): void {         this.loaderservice.hide();     } } 

app.module.ts

import { browsermodule } '@angular/platform-browser'; import { ngmodule } '@angular/core'; import { formsmodule,reactiveformsmodule } '@angular/forms'; import { httpmodule, http, xhrbackend, requestoptions } '@angular/http';  import { materialmodule } '@angular/material'; import 'hammerjs';  import { perfectscrollbarmodule } 'angular2-perfect-scrollbar'; import { perfectscrollbarconfiginterface } 'angular2-perfect-scrollbar'; import { select2module } 'ng2-select2'; import { modalmodule } "ng2-modal"; import { customformsmodule } 'ng2-validation' import { momentmodule } 'angular2-moment';  import { appcomponent } './app.component'; import { routing } './app.routes'; import { httpfactory } "./http.factory";  import { authservice } './services/auth.service'; import { authmanager, adminrole } './authmanager'; import { appsettings } './app.settings'; import { loaderservice } './factory/loader.service'; import { globaleventservice } './factory/globalevent.service'; import { custommessageservice } './factory/message.service'; import { sharedservice } './services/shared.service';  import { staticcmsservice } './services/static.service'; import { userservice } './services/users.service'; import { teacherservice } './services/teacher.service'; import { studentservice } './services/student.service'; import { chatservice } './services/chat.service';  import { headercomponent } './component/header/header.component'; import { footercomponent } './component/footer/footer.component'; import { logincomponent } './component/login/login.component'; import { navigationcomponent } './component/navigation/navigation.component'; import { loadercomponent } './component/loader/loader.component'; import { custommessage } './component/custom_msg/message.component'; import { deletepopupcomponent } './component/delete_popup/delete_popup.component';  import { teachercomponent } './component/teacher/teacher.component'; import { viewteachercomponent } './component/teacher/view/view.component';  import { studentcomponent } './component/student/student.component'; import { viewstudentcomponent } './component/student/view/view.component';  import { chatcomponent } './component/chat/chat.component'; import { termscomponent } './component/terms/terms.component'; import { policycomponent } './component/policy/policy.component'; import { faqcomponent } './component/faq/faq.component'; import { viewfaqcomponent } './component/faq/view/view.component'; import { addfaqcomponent } './component/faq/add/add.component';  import { routerestrictedcomponent } './component/restrict/restrict.component';  import { decimaltextpipe } './pipe/decimal_text.pipe';  const perfect_scrollbar_config: perfectscrollbarconfiginterface = {   suppressscrollx: true };  @ngmodule({   declarations: [     appcomponent,     headercomponent,     logincomponent,     footercomponent,     decimaltextpipe,     routerestrictedcomponent,     navigationcomponent,     loadercomponent,     custommessage,     deletepopupcomponent,     termscomponent,     policycomponent,     faqcomponent,     viewfaqcomponent,     addfaqcomponent,     teachercomponent,     viewteachercomponent,     studentcomponent,     viewstudentcomponent,     chatcomponent   ],   imports: [     browsermodule,     formsmodule,     reactiveformsmodule,     httpmodule,     routing,     materialmodule,     materialmodule.forroot(),     perfectscrollbarmodule.forroot(perfect_scrollbar_config),     select2module,     modalmodule,     customformsmodule,     momentmodule   ],   exports: [     loadercomponent     ],   providers: [     authmanager,     adminrole,     authservice,     appsettings,     sharedservice,     loaderservice,     custommessageservice,     staticcmsservice,     globaleventservice,     chatservice,     teacherservice,     studentservice,     userservice,     {         provide: http,         usefactory: httpfactory,         deps: [xhrbackend, requestoptions, loaderservice]     }   ],   bootstrap: [appcomponent] }) export class appmodule {} 

auth.service.ts

import { injectable, oninit } '@angular/core'; import { http, response, headers, requestoptions } '@angular/http'; import { router } '@angular/router' import { observable, behaviorsubject } 'rxjs/rx'; import { appsettings } '../app.settings';  import 'rxjs/add/operator/map'; import 'rxjs/add/operator/publishreplay';  @injectable() export class authservice implements oninit {     private currentuserdata: any;     constructor(         private _http: http,         private _headers: appsettings,         private _router: router     ){     }      ngoninit(){     }      isloggedin(){         if(!window.localstorage['key']){             return false;         }         else {             return true;         }     }      loginauth(creds){         return this._http.post('login',creds).map((res:response) => res.json()).share();     }      getcurrentuserdetails(){         if(!this.currentuserdata){             this.currentuserdata = this._http.get('getcurrentuserdetails').map((res:response) => res.json());         }         return this.currentuserdata;     }      logout(){         this._http.get('logout').map((res:response) => res.json()).subscribe(data => {             window.localstorage.removeitem('key');             this._router.navigatebyurl('/');             this.currentuserdata = null;         });     } } 

you have circular dependency : httpinterceptor new http service in module. authservice needs httpinterceptor , vice-versa.

the fact don't see real need of extending http service in code. create wrapper myhttp service inject http , use this.http.get(...),this.http.post(...),etc instead of super.get(...). , inject real http in authservice :

class httpinterceptor{    constructor(http:http,auth:authservice){} }  class authservice{    constructor(http:http){} } 

or join classes authservice , httpinterceptor single one, drawback every classes have login , logout methods.

as said in comments, don't know how app works can't think other way moment.


Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -