I have a Typescript application built with Angular 2. In this application, I need to retrieve Build Artifacts from a Jenkins server using the Jenkins Rest API. The Build Artifact contains a text file that I want to read from. I am making use of Angular's http.get() method to access the Jenkins URL. The response type I am expecting is text() since the file contains text. However, when I try to assign the response to a variable (this.data) in my component, the value does not get assigned.
//myservice.ts
import { Http, Response } from '@angular/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { AppConfig } from '../app.config';
@Injectable()
export class JenkinsService {
private jenkinsRestAPI;
constructor(private http: Http, private config: AppConfig) {
}
getTextFromJenkins(serviceName): Observable<string>{
this.jenkinsRestAPI= 'http://'+this.config.getConfig('jenkins')+'/job/'+serviceName
return this.http.get(this.jenkinsRestAPI)
.map(this.extractData)
.catch(this.handleError);
}
// Extracts data from response
private extractData(res: Response) {
if (res.status < 200 || res.status >= 300) {
throw new Error('Bad response status: ' + res.status);
}
let body = res.text();
return body || ''; // here
}
//mycomponent.ts
export class JenkinsComponent implements OnInit {
servicesList:Array<string> = ['Backend','DataService', 'demoService','SystemService']
data:string;
errorMessage: string;
serviceName:string;
constructor(private _jenkinsService: JenkinsService) {
}
ngOnInit() {
for(var i = 0; i < this.servicesList.length; i++){
this.serviceName=this.servicesList[i];
this.getValueFromJenkins(this.serviceName);
}
}
getValueFromJenkins(serviceName) {
this._jenkinsService.getTextFromJenkins(this.serviceName).subscribe(
textdata=> this.data= <string>textdata,
error => this.errorMessage = <any>error from server
);
}