2

我正在使用 Angular 4。我是 Angular 的新手。

我在另一个服务中找不到服务对象的问题。

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

我正在关注这个什么是angular2中的httpinterceptor等价物?开始我的解决方案。我已经提到了这里给出的所有解决方案。

一样,我对所有 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] } 
        ]

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

无法实例化循环依赖!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。

我和这里有同样的问题,如何在角度 2 中使用自定义 http 刷新访问令牌?

如何访问服务?:(

谢谢。

4

0 回答 0