Angular class 变量无法访问从服务返回的 Http 响应

Angular Http response returned from the service is not accessible to class variable

我有 Angular 2 Typescript 应用程序。我想在我的应用程序中使用 Jenkins Rest API 从 Jenkins 服务器访问构建工件。 Build Artifact 包含一个文本文件。我想从文件中读取文本。我正在使用 angular 中的 http.get() 来访问 jenkins url。返回的 responseType 是 text(),因为文件包含一些文本。当我尝试将返回的响应分配给组件中定义的变量 (this.data) 时,我没有看到分配给它的任何值。

    //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 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);
         // console.log(this.data);-- It shows undefined. No values seen

      } 
  }

 getValueFromJenkins(serviceName) {
    this._jenkinsService.getTextFromJenkins(this.serviceName).subscribe(
      textdata=>  this.data= <string>textdata, 
// textdata=>  console.log(textdata) -- here I can see the text values.
      error => this.errorMessage = <any>error from server
    );
    //console.log(this.data); --here I dont see any text values
  }

在您的 ngOnInit 中,当您调用 getValueFromJenkins 时,响应不会立即到达。这就是为什么在下一行 this.data 仍然未定义。响应稍后到达,在 .subscribe() 内。您至少有 3 个选项:

使用数据解析保护

Angular 允许您使用一种称为 Resolve Guard 的特殊服务,该服务将在路由加载过程中获取异步数据,并仅在数据到达后才初始化您的组件。这样做的好处是数据会在ngOnInit()内同步可用,所以组件加载和数据加载之间不会有延迟,异步操作也不会大惊小怪。这可能是最好的解决方案,但它需要修改您的路由配置并编写一个新服务 class。 See the docs

在 ngOnInit 中订阅

ngOnInit 中,您可以等到数据 return 时再使用它:

this._jenkinsService.getTextFromJenkins(this.serviceName).subscribe(
   result => this.data = result // note this happens later, once server returns data
);

使用async/await强制浏览器等待

async/await 关键字允许您像处理同步代码一样处理异步代码,方法是强制浏览器在继续执行下一行之前等待执行解析。要实施此方法,首先更改 getValueFromJenkins() 并将其设为 return 承诺:

getValueFromJenkins(serviceName):Promise {
  // will subscribe and convert the result to a promise that will resolve
  // with the server's response
  return this._jenkinsService.getTextFromJenkins(serviceName).toPromise();
}

接下来,将ngOnInit标记为async;你可以这样获取数据:

async ngOnInit() {
  for(let i = 0; i < this.servicesList.length; i++){
    try{
      this.data = await this.getValueFromJenkins(this.servicesList[i]);
      console.log(this.data); // should work!
    }catch(e) { /* Handle error here */}
  }
}