现在我正在尝试使用Angular2 Router.navigate,但它不起作用。
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
}
}
但是当调用handleServerError时,它显示错误"无法读取undefined"的属性导航。
在服务中使用路由器是不可能的吗?
答案 0 :(得分:0)
更改以下行
this._router.navigate(['登录']); => this._router.navigate([' / login']);