无法在服务Angular 2中读取未定义的属性“导航”

时间:2017-02-14 13:05:27

标签: angular typescript

我正在一个服务中对服务器进行http请求,然后我想在其他服务中提取响应。如果响应错误,我想在错误页面上重定向用户。

DataService.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import './../rxjs-operators';
import { Json } from './models/json';
import { ResponseService } from './providers/response.service';
import { ErrorService } from './providers/error.service';

@Injectable()
export class DataService {
    constructor(private http: Http,
        private responseService: ResponseService,
        private errorService: ErrorService) { }

    getData(): Observable<Json> {
        return this.http
            .get(this.getDataUrl)
            .map(this.responseService.extractData)
            .catch(this.errorService.handleError);
    }
}

ResponseService.ts

import { Injectable } from '@angular/core';
import { Response } from '@angular/http';
import { Router } from '@angular/router';
import { Json } from './models/json';

@Injectable()
export class ResponseService {
    constructor(private router: Router) { }

    extractData(response: Response) {
        let json: Json = response.json();
        if (json.status === 'success') {
            return json.data;
        } else {
            let errorId: number = json.data;
            console.log(this.router);
            this.router.navigate(['something-went-wrong'], { queryParams: { errorId: errorId } });
            return null;
        }
    }
}

但我有错误Cannot read property 'navigate' of undefined,当我在控制台中打印router时,我看到undefined

我该如何解决?

0 个答案:

没有答案