0
아래 rest service를 작성했지만 this.router.navigate ([ '/ login'])를 호출 할 때 오류가 발생합니다. 서비스중인 라우터 객체를 만드는 방법은 무엇입니까? this.router.navigate는 Component 클래스에서 작동하지만 서비스에서는 작동하지 않습니다.각도 2 경로 서비스중인 라우터 객체를 만드는 방법은 무엇입니까?
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는 아무것도 가지고 있지 않다. 나는 라우터의 객체를 생성하는 문제가 있다고 생각한다. –