I'm currently developing an application using Angular 5, and I want to segregate raw http calls into their own services so that other services can modify the responses as needed. This involves having a component, component service, and component data service.
My question is how can I chain observables following this design pattern? Below is my attempted code:
licenseData.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams, HttpErrorResponse } from '@angular/common/http';
import { CONSTANT } from '../../environment/constants';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/throw';
@Injectable()
export class LicenseDataService {
constructor(private http: HttpClient) {}
getLicenseInfo() {
const params = new HttpParams()
.set('unsername', 'swapp')
.set('comment', "hi");
const endpoint = '/myendpoint';
return this.http
.get(endpoint, {params: params})
.map((response) => {
console.log(' response ', response);
//return Observable.of<any>(response);
return response['data'];
})
.catch(this.errorHandler);
}
errorHandler(error: HttpErrorResponse) {
//TODO: log the error here
return Observable.throw(error);
}
}
license.service.ts
import { Injectable } from '@angular/core';
//import { Observable } from 'rxjs/Observable';
import { LicenseDataService } from './licenseData.service';
@Injectable()
export class LicenseService {
constructor(private licenseDataService: LicenseDataService) { }
getVersion() {
//handle the error in here and the loading as well
return this.licenseDataService.getLicenseInfo()
.subscribe((response) => {
return response['versionNumberField'];
});
//console.log(' result ', result);
//return result['versionNumberField'];
}
}
and here is part of my component code:
export class AboutComponent implements OnInit {
//version: Observable<string>;
version: string;
constructor(private licenseService: LicenseService) {
console.log('Hello Component');
}
ngOnInit() {
console.log('ngOnInit');
//this.version = this.licenseService.getVersion();
this.licenseService.getVersion()
.subscribe(response => this.version = response);
}
}
My project won't build. How can I properly chain these components?