2

I am working with angular 4. I am newbie in angular.

I have problem with service object couldn't find in another service.

I am working for 401 status error to get refresh token on token expired.

I am following this What is httpinterceptor equivalent in angular2? to start my solution. I have referred all solution given here.

As par this and this I have following Service for all Http request call.

default-http.ts

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<Response> {
        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<Response>): Observable<Response> {

        return observable.catch((err, source) => {
            let body = err.json();
            if (err.status == 401 && 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 => {
                            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) 
}

Here my app.module code to define provider.

//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 { }

with this code I get error

Cannot read property 'getRefreshToken' of undefined

If I replace provider with bellow code

providers: [            
            AdminAuthService,
            { provide: Http, useFactory: httpProvider, deps: [XHRBackend, RequestOptions, AdminAuthService] } 
        ]

AdminAuthService in deps parameter, I receive bellow error:

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

In getRefreshToken I have code to get refresh token from Node server.

Here my adminauth.service 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<string> {

        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) => {
                let res = response.json();

                let token = res && res.access_token;
                if (token) {
                    //store token in cookie or localstorage
                    return res;
                }

            }).catch(this.handleError);
    }
}

Can anyone please help me to solve this problem. How I can use my AdminAuthService in DefaultHttp class.

I have same question as here how to refresh the access token using custom http in angular 2?

How to access service? :(

Thanks.

Community
  • 1
  • 1
herr
  • 837
  • 1
  • 8
  • 21

0 Answers0