title: angular 4 provider and Dependency Injection issue with service object in constructor of service
body: <p>I am working with angular 4. I am newbie in angular.</p>
  
  <p>I have problem with service object couldn't find in another service.</p>
  
  <p>I am working for 401 status error to get refresh token on token expired.</p>
  
  <p>I am following this <a href="https://stackoverflow.com/questions/35498456/what-is-httpinterceptor-equivalent-in-angular2/35499034#35499034">What is httpinterceptor equivalent in angular2?</a> to start my solution. I have referred all solution given here.</p>
  
  <p>As par <a href="https://www.illucit.com/blog/2016/03/angular2-http-authentication-interceptor/" rel="nofollow noreferrer">this</a> and <a href="https://stackoverflow.com/questions/34907151/handling-refresh-tokens-using-rxjs">this</a> I have following Service for all Http request call. </p>
  
  <p>default-http.ts</p>
  
  <pre><code>import { Injectable } from "@angular/core";
  import { Http, Request, RequestOptionsArgs, Response, XHRBackend, RequestOptions, ConnectionBackend, Headers} from '@angular/http';
  import { Router} from '@angular/router';
  
  import { Observable } from 'rxjs/Observable';
  import 'rxjs/add/operator/catch';
  
  import { AdminAuthService } from '../../admin/auth/service/adminauth.service';
  
  @Injectable()
  export class DefaultHttp extends Http {
  
      constructor(
          backend: ConnectionBackend, 
          defaultOptions: RequestOptions,
          private router: Router,
          private adminAuthService: AdminAuthService,
          ) {
  
          super(backend, defaultOptions);
          console.log(this.adminAuthService); // didn't get this object it's undefined
      }
  
      request(url: string | Request, options?: RequestOptionsArgs): Observable&lt;Response&gt; {
          return this.intercept(super.request(url, options));
      }
  
      getRequestOptionArgs(options?: RequestOptionsArgs): RequestOptionsArgs {
          // here set authorization header
          if (options == null) {
              options = new RequestOptions();
          }
          if (options.headers == null) {
              options.headers = new Headers();
          }
          return options;
      }
  
      intercept(observable: Observable&lt;Response&gt;): Observable&lt;Response&gt; {
  
          return observable.catch((err, source) =&gt; {
              let body = err.json();
              if (err.status == 401 &amp;&amp; body.error_code == 'invalid_token') 
              {
                      //here also I couldn't get getRefreshToken function as there is no adminAuthService object is available.
                      this.adminAuthService.getRefreshToken()
                          .mergeMap(response =&gt; {
                              var res = JSON.parse(JSON.stringify(response));
                              if(res.access_token)
                              {
                                  //here how to call request again
                                  return this.request(err.url, err.options);
                              }
                              else {
                                  this.router.navigate(['/admin/login']);
                              }
                          });
                  return Observable.empty();
              } else {
                  return Observable.throw(err);
              }
          });
  
      }
  }
  
  export function httpProvider(xhrBackend: XHRBackend,
                          requestOptions: RequestOptions,
                          router: Router,
                          adminAuthService: AdminAuthService)
  { 
      return new DefaultHttp(xhrBackend, requestOptions, router, adminAuthService) 
  }
  </code></pre>
  
  <p>Here my app.module code to define provider.</p>
  
  <pre><code>//other required import statements.
  import { httpProvider } from './common/service/default-http';
  import { AdminAuthService } from './admin/auth/service/adminauth.service';
  
  @NgModule({
      declarations: [
          AppComponent,
          NotFoundComponent
      ],
      imports: [
          BrowserModule,
          FormsModule,
          HttpModule,
          AppRoutingModule
      ],
      providers: [            
          AdminAuthService,
          { provide: Http, useFactory: httpProvider, deps: [XHRBackend, RequestOptions] } 
      ],
    bootstrap: [AppComponent]
  })
  export class AppModule { }
  </code></pre>
  
  <p>with this code I get error </p>
  
  <blockquote>
    <p>Cannot read property 'getRefreshToken' of undefined</p>
  </blockquote>
  
  <p>If I replace provider with bellow code</p>
  
  <pre><code>providers: [            
              AdminAuthService,
              { provide: Http, useFactory: httpProvider, deps: [XHRBackend, RequestOptions, AdminAuthService] } 
          ]
  </code></pre>
  
  <p>AdminAuthService in deps parameter, I receive bellow error:</p>
  
  <blockquote>
    <p>Cannot instantiate cyclic dependency! Http: in NgModule AppModule in
    ./AppModule ; Zone:  ; Task: Promise.then ; Value: Error:
    Provider parse errors:(…) Error: Provider parse errors: Cannot
    instantiate cyclic dependency! Http: in NgModule AppModule in
    ./AppModule</p>
  </blockquote>
  
  <p>In getRefreshToken I have code to get refresh token from Node server.</p>
  
  <p>Here my adminauth.service code:</p>
  
  <pre><code>@Injectable()
  export class AdminAuthService {
  
      private requestUrl = globals.requestUrl;
      private options: RequestOptions;
      constructor(private http: Http, private cookieStorage: CookieService) {
  
          this.options = new RequestOptions({
              headers: new Headers({ 'Content-Type': 'application/json;charset=UTF-8' }) 
          });
      }
      getRefreshToken(): Observable&lt;string&gt; {
  
          let basicToken = "Basic "+localStorage.getItem('basicToken');
  
          let options = new RequestOptions({
              headers: new Headers({ 'Content-Type': 'application/json;charset=UTF-8', 'Authorization': basicToken }) 
          });
          let refreshtoken = {grant_type: 'refresh_token', refresh_token: this.cookieStorage.get('refreshToken')};
          let url = this.requestUrl+'/login';
  
          return this.http.post(url,JSON.stringify(refreshtoken), options)
              .map((response: Response) =&gt; {
                  let res = response.json();
  
                  let token = res &amp;&amp; res.access_token;
                  if (token) {
                      //store token in cookie or localstorage
                      return res;
                  }
  
              }).catch(this.handleError);
      }
  }
  </code></pre>
  
  <p>Can anyone please help me to solve this problem. How I can use my AdminAuthService in DefaultHttp class.</p>
  
  <p>I have same question as here <a href="https://stackoverflow.com/questions/42645350/how-to-refresh-the-access-token-using-custom-http-in-angular-2">how to refresh the access token using custom http in angular 2?</a></p>
  
  <p>How to access service? :(</p>
  
  <p>Thanks.</p>