0

Now I am trying to use Angular2 Router.navigate, but it isn't working.

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';

@Injectable()
export class HttpService {

    constructor(
        public _http: Http,
        public _router: Router
        ) 
    {
    }

    public sendPostRequestWithParams(url, params) {
        let headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded');

        return this._http.post(url, params, {headers: headers})
        .map(res => res.json())
        .catch(this.handleServerError);
    }

    public handleServerError(error: Response) {
        let jError = error.json() && error.json()['error'];
        if (jError == 'Unauthenticated.') {
            alert("You are not unauthenticated. Please login correctly!");
            this._router.navigate(['login']);
            return Observable.throw("You are not unauthenticated. Please login correctly!");
        }
        return Observable.throw(error.json() || 'Server error'); // Observable.throw() is undefined at runtime using Webpack
    }

}

But when calling handleServerError, it shows error "Cannot read property navigate of undefined".

Is it impossible to use Router in Service?

eko
  • 39,722
  • 10
  • 72
  • 98
LarAng
  • 1,255
  • 3
  • 18
  • 28

1 Answers1

0

Change below line

this._router.navigate(['login']); => this._router.navigate(['/login']);