在@injectable类中未定义路由器

时间:2017-10-13 14:02:36

标签: angular typescript angular-router

由于某种原因router在我的班级中未定义,有人可以对此有所了解吗?

import { Injectable } from '@angular/core';
import { XHRBackend, RequestOptions, Response, Headers } from '@angular/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import { AuthService } from './auth.service';
import { ApiService } from './api.service';

@Injectable()
export class AuthApiService extends ApiService {
    constructor (
        private auth: AuthService,
        public router: Router,
        backend: XHRBackend,
        options: RequestOptions,
   ) {
       super(router, backend, options);
       const token = this.auth.getToken();
       options.headers.set('Authorization', `Bearer ${token}`);
   }

   public handleError(error: Response) {
       super.handleError(error);

       console.log(this.router); // <- undefined

       return Observable.throw(error);
   }
}

API类

import { Injectable } from '@angular/core';
import { Http, XHRBackend, RequestOptions, Request, RequestOptionsArgs, Response } from '@angular/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import { AuthService } from './auth.service';

@Injectable()
export class ApiService extends Http {
  constructor (
    public router: Router,
    backend: XHRBackend,
    options: RequestOptions
  ) {
    super(backend, options);
  }

  public request(url: string|Request, options?: RequestOptionsArgs):     Observable<Response> {
    return super.request(url, options).catch(this.handleError);
  }

  public handleError(error: Response) {
    return Observable.throw(error);
  }

}

1 个答案:

答案 0 :(得分:1)

我今天有同样的问题。问题是:在函数handleError中,'this'不是指向AuthApiService,而是一个新的上下文。您需要像这样修改handleError函数:

public handleError(self){
    return (error: Response) => {
        super.handleError(error); 
        console.log(self.router);

        return Observable.throw(error);
    }
}

通过传递对的引用来调用此函数 AuthApiService .catch(this.handleError(this))