2016-08-31 7 views
1

私はサービスを使ってリクエストしています。angular2 RC5:platform-b​​rowser.umd.js:937例外:エラー:キャッチされていない(約束しています):

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') 
    } 
} 

そして、私は私のテンプレートにthis:

{{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}} 

デバッグは、私はそれが値を返すことを保証するために作成する特別なパイプであり、それは返します怒鳴る値:

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

しかし、私はdescriptionプロパティまたはを使用しようとするとプロパティは、私が前に述べたエラーを返します。

これはどうなるのでしょうか?

すべてのヘルプが歓迎されています。

答えて

2

初めてデータを非同期に取得すると、変数shortDescriptionundefinedになります。

Elvis operatorはあなたの問題を解決する必要があります。

{{shortDescription?.description}} 

その他のオプション

1)ngIf構造ディレクティブを使用します。

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

2)

初期値を設定します
export class HomeComponent implements AfterViewInit, OnInit { 
    private shortDescription = { description: '' }; 
    ... 
+0

エルヴィスの演算子を使いたくない場合は、どうすればいいですか? これは機能しますが、これを解決する別の方法がありますか? –

+0

私は答えを更新しました – yurzui

+0

今、私はこのコンセプトを理解して、ありがとう! –

関連する問題