2016-08-23 66 views
0

我創建了下面的休息服務,但在調用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')); 
    } 
} 

回答

0

嘗試this.router.navigate(['login']);來代替。路由器將斜線本身作爲服務器URI的一部分。

+0

我有調試它,this.router什麼也沒有。我認爲有路由器的創建對象的問題。 –

相關問題