angular 2 RC5:platform-b​​rowser.umd.js:937 EXCEPTION:错误:未捕获(在承诺中):

时间:2016-08-31 14:55:45

标签: angular angular-rc5

我正在使用服务来提出请求。

homepage.service.ts

import { Injectable } from "@angular/core";
import { Http, Response } from "@angular/http";

import { Observable } from "rxjs/Observable";
import { PATH } from "../const/config";

import { SliderRequest } from "../request/slider.request";

@Injectable()

export class HomepageService {
    private sliderUrl = PATH.url.getUrl();
    constructor (private _http: Http) {}
    getSlider(): Observable<SliderRequest> {
        let doRequest = this._http.get(this.sliderUrl.slider).map(
            (res) => {
                let response = res.json();
                return response;
            }
        );
        return doRequest;
    }
}

我将此服务用于主页组件

homepage.component.ts

import { Component, AfterViewInit, OnInit } from "@angular/core";
import { CONFIG, PATH } from "../../const/config";

import { Inject } from "../../inject/inject";

// import service
import { HomepageService } from "../../services/homepage.service";

@Component({
    selector: 'app-home',
    templateUrl: CONFIG.baseUrlForComponentView("home"),
    providers: [HomepageService]
})

export class HomeComponent implements AfterViewInit, OnInit {
    private sliders: any[];
    private shortDescription: any[];
    constructor( private homeService:  HomepageService) {}
    ngOnInit() {
        let that = this;
        this.homeService.getSlider().subscribe(
            (response) => {
                var data = response.data;
                this.shortDescription = data.shortDescription.text;
            }
        );
    }
    ngAfterViewInit() {
        Inject.load(PATH.javascript, 'global')
    }
}

在我的模板中,我这样做:

{{shortDescription.description}}

它返回错误:

platform-browser.umd.js:937 EXCEPTION: Error: Uncaught (in promise): EXCEPTION: Error in public/templates/view/home.tpl.html:0:0
ORIGINAL EXCEPTION: TypeError: Cannot read property 'description' of undefined
ORIGINAL STACKTRACE:
TypeError: Cannot read property 'description' of undefined

所以我试试这个:

{{shortDescription | debug}}

debug是我创建的一个特殊管道,用于确保它返回值,并返回以下值:

"shortDescription": {
            "video": {
                "url": ""
            },
            "text": {
                "description": "<strong>Lorem</strong>ipsum",
                "goTo": "le concept"
            }
        }

但是如果我尝试使用description属性或goTo属性,它会返回我之前提到的错误。

并不明白这会发生什么?

欢迎所有帮助!

1 个答案:

答案 0 :(得分:2)

由于您在第一次变量shortDescription等于undefined时异步获取数据。

Elvis operator应解决您的问题:

{{shortDescription?.description}}

其他选项

1)使用结构指令 ngIf

<template *ngIf="shortDescription">
  {{shortDescription.description}}
</template>

2)设置初始值

export class HomeComponent implements AfterViewInit, OnInit {
  private shortDescription = { description: '' };
  ...