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

时间:2017-08-29 14:58:13

标签: angular typescript angular-http

我正在使用Angular 2 Typescript应用程序。我想在我的应用程序中使用Jenkins Rest API从Jenkins服务器访问Build Artifacts。 Build Artifact包含一个文本文件。我想从文件中读取文本。我使用angular中的http.get()来访问jenkins网址。返回的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
  }

1 个答案:

答案 0 :(得分:1)

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

使用Data Resolve Guard

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

订阅ngOnInit

ngOnInit中,您可以等到数据返回使用它:

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

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

async / await关键字允许您使用异步代码,就好像它是同步的一样,强制浏览器等待执行解析,然后再转到下一行。要实现此方法,首先更改getValueFromJenkins()并使其返回承诺:

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 */}
  }
}