Angular 2 route如何在服务中创建路由器对象?
问题描述:
我创建了下面的休息服务,但在调用this.router.navigate(['/ login'])时出错。如何在服务中创建路由器对象? this.router.navigate是来自Component类的工作,但它不能从服务中工作。Angular 2 route如何在服务中创建路由器对象?
import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { apiURL } from './app.config';
@Injectable()
export class RestService {
header = new Headers();
constructor(public http: Http, private router: Router) {
}
get(url: string) {
debugger;
this.addHeader();
return this.http.get(apiURL + url, { headers: this.header }).catch(this.handleError);;
}
post(url: string, data) {
this.addHeader();
return this.http.post(apiURL + url, data, { headers: this.header }).catch(this.handleError);;
}
put(url: string, data) {
this.addHeader();
return this.http.put(apiURL + url, data, { headers: this.header }).catch(this.handleError);;
}
auth(url: string, data) {
this.addHeader();
return this.http.post(apiURL.replace('api/v1/', '') + '/' + url, data, { headers: this.header }).catch(this.handleError);
}
private extractData(res: Response) {
debugger;
let body = res.json();
return body.data || {};
}
private handleError(error: any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
debugger;
if (error.status == '401') {
this.router.navigate(['/login']);
}
else {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
}
private addHeader() {
this.header = new Headers();
this.header.append('Content-Type', 'application/json');
this.header.append('Authorization', 'Bearer ' + localStorage.getItem('id_token'));
}
}
答
尝试this.router.navigate(['login']);
来代替。路由器将斜线本身作为服务器URI的一部分。
我有调试它,this.router什么也没有。我认为有路由器的创建对象的问题。 –