如何在 Angular2 中处理 "Cannot convert undefined or null to object"

How to tackle "Cannot convert undefined or null to object" in Angular2

我已经为 API 调用编写了一个服务来获取数据。下面是我的服务代码。

  export class SurveyServiceService {

  private surveysUrl = 
  'http://107.170.59.79/services/public/api/v1/countries';
  private headers = new Headers({'Content-Type': 'application/json'});

  constructor(private http: Http) { }

  getSurveys(): Promise<Survey[]> {
    return this.http.get(this.surveysUrl)
       .toPromise()
       .then(response => response.json() as Survey[])
       .catch(this.handleError);
  }
 }

下面是我的 getSurveys 函数组件

export class SurveysComponent implements OnInit {

  title = 'Survey List';
  surveys: Survey[];
  keys: String[];
  selectedSurvey: Survey;

  constructor(private router: Router,
    private surveyService: SurveyServiceService) { }

  ngOnInit(): void {
    this.getSurveys();
    this.keys = Object.keys(this.surveys);
  }

  getSurveys(): void {
    this.surveyService.getSurveys().then(surveys => this.surveys = surveys);
  }
 }

因为我在 json 对象中获取数据,所以我尝试使用以下代码将其转换为数组,以便我可以在 HTML.

中使用 *ngFor 对其进行迭代
this.keys = Object.keys(this.surveys);

但是当我 运行 代码时,我收到一个错误

TypeError: Cannot convert undefined or null to object

谁能告诉我哪里出错了?

@JB Nizet 的评论是正确的解决方案,我把答案放在这里是为了清楚代码。

export class SurveysComponent implements OnInit {

  title = 'Survey List';
  surveys: Survey[];
  keys: String[];
  selectedSurvey: Survey;

  constructor(private router: Router,
    private surveyService: SurveyServiceService) { }

  ngOnInit(): void {
    this.getSurveys().then(surveys => {
       this.surveys = surveys;
       this.keys = Object.keys(this.surveys);
    });
  }

  getSurveys(){
    return this.surveyService.getSurveys();
  }
 }

我尝试使用管道,但遇到了与您相同的问题。 相反,我将其用作解决方法。

.subscribe(
    res =>
    {
    this.apiarray = []; <--- Empty array here
    console.log("response form api :  " + JSON.stringify(res));
    this.ResultfromApi= res;
    this.apiarray.push(this.PatientInfoFromApi);
    }

现在您只需遍历数组而不是对象。在模板中, 你的 *ngFor 循环是这样的

<tr *ngFor="let item of apiarray">
  <td>{{item.specific_key_to_your_result}}</td>
  ...
</tr>