사라 나는 일부 데이터 가져 오기 위해 다시 서버로 이동하는 간단한 서비스입니다 다음과 같은 코드를 가지고는 handleError을 제외하고 예상대로각도이 개 private 변수는
import { Injectable } from '@angular/core';
import { Action } from '../shared';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Authenticated } from '../authenticated';
import 'rxjs/Rx';
@Injectable()
export class ActionsService {
private url = 'http://localhost/api/actions';
constructor(private http: Http, private authenticated : Authenticated) {}
getActions(search:string): Observable<Action[]> {
let options = this.getOptions(false);
let queryString = `?page=1&size=10&search=${search}`;
return this.http.get(`${this.url + queryString}`, options)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(response: Response) {
let body = response.json();
return body || { };
}
private handleError (error: any) {
let errMsg = (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
if (error.status == 403) {
this.authenticated.logout();
}
return Observable.throw(errMsg);
}
private getOptions(addContentType: boolean) : RequestOptions {
let headers = new Headers();
if (addContentType) {
headers.append('Content-Type', 'application/json');
}
let authToken = JSON.parse(localStorage.getItem('auth_token'));
headers.append('Authorization', `Bearer ${authToken.access_token}`);
return new RequestOptions({ headers: headers });
}
}
모든 작동합니다. getActions가 서버로부터 에러를 받자 마자 this.authenticated.logout()이 호출되어야하는 섹션까지 다시 작동하는 this.handleError 메소드로갑니다. this.autenticated는 정의되지 않았고, "this"가 다른 객체를 참조하고 있거나 ActionSerivce의 로컬 변수가 null이되고 http 예외가 발생했기 때문에 이것이 맞는지 확실하지 않습니다. 인증 된 지역 변수가 적절하게 주입되었습니다 (생성자에서 console.log를했는데 거기에있었습니다).
대단히 고마워. –