【问题标题】:Angular2: Http Client and reading from JSON containing a single objectAngular2:Http客户端并从包含单个对象的JSON读取
【发布时间】:2016-03-19 21:23:04
【问题描述】:

我正在调查 Angular2 Http 客户端,但我不知道为什么我不能执行以下操作。

我阅读了以下 JSON 文件:

{
  "id": 1,
  "surveyType": "Type1"
}

进入:

export class Survey {
    constructor(public id:number, public surveyType:string) {

    }
}

使用 HTTP 客户端。

在我的服务中,我调用 HTTP GET:

getSurvey() {
    return this.http
        .get(this.surveyUrl)
        .map((response:Response) => <Survey>response.json());
}

而在我的组件中我有:

survey:Survey;

ngOnInit() {
    this.getSurvey();
}


getSurvey() {
    this.surveyService.getSurvey()
        .subscribe(
            (survey:Survey) => {
                this.survey = survey;
                console.log(this.survey);
            },
            error => console.log(error)
        );
}

我的模板只包含:

<h1>{{survey.id}}</h1>

执行代码时,总是出错。

TypeError: Cannot read property 'id' of undefined in [{{survey.id}} in SurveyComponent@0:4]

堆栈跟踪中的上下文变量读取:

context
    SurveyComponent
        survey
            Object id: 1, surveyType: Type1

我也在控制台中看到了这个对象:

Object {id: 1, surveyType: "Type1"}

我的担忧:

  1. 为什么返回的对象不是 Survey 类型?
  2. 为什么我的调查对象无法使用表达式显示?
  3. 最后,我怎样才能让这样的例子工作? API 返回单个对象,而不是数组。

我正在使用 Angular2 Beta 11。

提前致谢!

【问题讨论】:

标签: angular


【解决方案1】:

由于survey的值是异步加载的,所以一开始它的值是未定义的。您需要在尝试使用 ngIf 显示其 id 属性之前对其进行检查:

<h1 *ngIf="survey">{{survey.id}}</h1>

或使用 Elvis 运算符作为 Eric 在评论中的暗示:

<h1>{{survey?.id}}</h1>

【讨论】:

    【解决方案2】:

    正如 Eric 提到的,使用 elvis 运算符或为属性 init 的调查提供一些虚拟默认值。

    private survery: Survey = {
        id: null,
        surveyType: ''
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-01
      • 2019-01-31
      • 2020-12-23
      • 1970-01-01
      • 1970-01-01
      • 2020-03-16
      • 2021-03-03
      相关资源
      最近更新 更多