I'm quite new with Angular but i would make a very simple thing (and i'm not able to do)...I want to create a 'base service' which communicates with my api backend but before sets some stuff(headers, variable ... and so)... all others services have to call this 'base service' to communicate with api...here my code:
import { Injectable } from '@angular/core';
import { HttpClient, HttpRequest, HttpHeaders, HttpParams, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Rx';
import { responseModel } from '../models/response.model';
@Injectable()
export class BaseService {
public headers: HttpHeaders;
constructor(private _http: HttpClient) {
this.headers = new HttpHeaders();
this.headers.append('Accept', 'application/json, */*');
this.headers.append('Content-Type', 'application/json;charset=UTF-8');
}
private callBackEnd(relativeEndPoint: string,reqMethod: string,
reqParams?: HttpParams, objBody?: any): Observable<responseModel> {
const reqUrl = 'https://mypath/' + relativeEndPoint;
return this._http.request<responseModel>(reqMethod, reqUrl,
{
body: objBody,
headers: this.headers,
params: reqParams,
responseType: 'json',
withCredentials: true
}
);
}
handleError(error: any): Observable<responseModel> {
const out: responseModel= {
error: !error.ok,
code: "10",
message: "no connection",
more_info: "info@cr",
response: {}
}
return Observable.create(observer => {
observer.next(out);
observer.complete();
});
}
}
it's very simple...every service in which there's a DI of 'BaseService' can call
/*IMPORT EVERYTHING*/
@Injectable()
export class CustomService {
constructor(private _http: BaseService) {
}
examplefunction(): Observable<responseModel>
{
return this._http.callBackEnd( '/user/', 'GET')
.map(
response => {
console.log( JSON.stringify(response));
return response;
}
)
}
}
I create a simple Component
import { Component, OnInit } from '@angular/core';
import { CustomService } from './CustomService.service';
import { responseBE } from '../global/models/response.model';
@Component({
selector: 'app-simple',
templateUrl: './simple.component.html',
styleUrls: ['./simple.component.css']
})
export class SimpleComponent implements OnInit {
constructor(private _service: CustomService ) { }
ngOnInit() {
this._service.examplefunction()
.map(res => {
console.log(res);
});
}
}
but nothing works :(
any idea?