角度4提供者和依赖注入问题与服务构造函数中的服务对象

时间:2017-04-11 06:41:18

标签: angular dependency-injection refresh-token

我正在使用角度4.我是角色的新手。

我遇到服务对象无法在其他服务中找到的问题。

我正在处理401状态错误,以便在令牌过期时获取刷新令牌。

我正在关注此What is httpinterceptor equivalent in angular2?以启动我的解决方案。我已经提到了这里给出的所有解决方案。

作为标准thisthis我有所有Http请求调用的服务。

默认-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) 
}

这是我的app.module代码,用于定义提供程序。

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

使用此代码我收到错误

  

无法读取未定义的属性'getRefreshToken'

如果我用波纹管代码替换提供商

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

deps参数中的AdminAuthService,我收到以下错误:

  

无法实例化循环依赖! Http:在NgModule AppModule中   ./AppModule;区域:;任务:Promise.then;值:错误:   提供程序解析错误:(...)错误:提供程序解析错误:不能   实例化循环依赖! Http:在NgModule AppModule中   ./AppModule

在getRefreshToken中,我有代码从节点服务器获取刷新令牌。

这是我的adminauth.service代码:

@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);
    }
}

任何人都可以帮我解决这个问题。我如何在DefaultHttp类中使用我的AdminAuthService。

我有同样的问题how to refresh the access token using custom http in angular 2?

如何访问服务? :(

感谢。

0 个答案:

没有答案