Angular2中的自定义Http服务。循环依赖性错误

时间:2017-08-17 08:01:45

标签: angular angular2-services

我已经创建了自定义Http服务来覆盖“请求”方法,如果需要,它会更新每个请求上的令牌。但问题是我收到“循环依赖”错误。知道怎么解决吗?

自定义Http服务:

import { Injectable } from '@angular/core';
import {
    Request, XHRBackend, RequestOptions, Response, Http, RequestOptionsArgs, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import {UserService} from "../services/user.service";

@Injectable()
export class VodHttpService extends Http {

    constructor(backend: XHRBackend, defaultOptions: RequestOptions, private userService : UserService ) {

        super(backend, defaultOptions);
    }

    request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {

        //adding access token to each http request before calling super(..,..)
        let token = this.userService.token;
        if (typeof url === 'string') {
            if (!options) {
                options = { headers: new Headers() };
            }

            if ( url != this.userService.PUBLIC_TOKEN_URL ) {
                options.headers.set('Authorization', `Bearer ${token}`);
            }
        }
        else {

            if ( url.url != this.userService.PUBLIC_TOKEN_URL ) {
                url.headers.set('Authorization', `Bearer ${token}`);
            }
        }

        console.log(url);

        return super.request(url, options)
            .catch((error) => {
                //if got authorization error - try to update access token
                if (error.status = 401) {
                    return this.userService.updateToken()
                        .flatMap((result: boolean) => {
                            //if got new access token - retry request
                            if (result) {
                                return this.request(url, options);
                            }
                            //otherwise - throw error
                            else {
                                return Observable.throw(new Error('Can\'t refresh the token'));
                            }

                        })
                }
                else {
                    Observable.throw(error);
                }
            })

    }

}

我的单身用户服务看起来像:

import {Component, Injectable, Injector} from '@angular/core';
import {Http} from "@angular/http";
import {Observable} from "rxjs";
import {environment} from "../../environments/environment";

@Injectable()
export class UserService {

    public token : string;
    public PUBLIC_TOKEN_URL = environment.token_url;

    constructor (private _http: Http) { }

    updateToken() : Observable<boolean> {

        let url = this.PUBLIC_TOKEN_URL;

        return this._http.get(url).map( res => {

            // return res.json();
            if (typeof res.json().access_token !== 'undefined'){

                this.token = res.json().access_token;
                return true;
            } else {

                return false;
            }
        });
    }

}

我知道通过使用Injector来修复它的方法,但我认为这是一种丑陋的方法。

1 个答案:

答案 0 :(得分:1)

自定义VodHttpService的提供程序定义不正确。它应该是这样的:

export function vodHttpFactory(backend: XHRBackend, options: RequestOptions, userService: UserService) {
      return new VodHttpService(backend, options, userService);
    }

@NgModule({
// other stuff 
providers: [ 
    UserService,
    {
      provide: VodHttpService,
      useFactory: vodHttpFactory,
      deps: [XHRBackend, RequestOptions, UserService]
    }
  ]
})

请注意,vodHttpFactory函数的编写方式与AOT兼容,以备不时之需。