我试图尽可能地分离我的代码并且我有数据服务,我在构造函数中初始化头文件,但它们没有被设置。
方法是构造函数中的SetHeaders()。标头没有设置。我是否必须在组件中使用OnInit?
import { Headers, Http, Response, Request, RequestOptions } from '@angular/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { AuthService } from '../../auth/resourceownerpassword/services/auth.service';
import { environment } from '../../../../environments/environment';
@Injectable()
export class DataService {
private _endpointUrl: string;
private _headers: Headers;
private _options: RequestOptions;
private _apiEndpoint: string;
public data: any;
constructor(public http: Http, public authService: AuthService) {
this.SetHeaders();
}
public SetEndpoint(endpointUrl: string) {
this._endpointUrl = environment.API_URL + endpointUrl;
}
public SetHeaders() {
console.log('setHeaders started');
this._headers = new Headers();
this._headers.append('Content-Type', 'application/json');
this._headers.append('Accept', 'application/json');
let token = this.authService.GetToken();
console.log("Token auth serv: " + token);
if (token !== '') {
let tokenValue = 'Bearer ' + token;
console.log('tokenValue:' + tokenValue);
this._headers.append('Authorization', tokenValue);
}
this._options = new RequestOptions({ headers: this._headers });
}
public Get = (): Observable<any[]> => {
return this.http.get(this._endpointUrl, this._options).map((response: Response) => <any[]>response.json());
}
public GetSingle = (id: number): Observable<any> => {
return this.http.get(this._endpointUrl + '/' + id, this._options).map(res => <any>res.json());
}
public Post = (item: any): Observable<any> => {
return this.http.post(this._endpointUrl, JSON.stringify(item), this._options).map(res => <any>res.json());
}
public Put = (item: any): Observable<any> => {
return this.http.put(this._endpointUrl, JSON.stringify(item), this._options).map(res => <any>res.json());
}
public Delete = (id: number): Observable<any> => {
return this.http.put(this._endpointUrl + '/' + id, null, this._options).map(res => <any>res.json());
}
}