Reputation: 7004
I'm using service to make a request.
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;
}
}
And I use this service into homepage component
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')
}
}
And into my template I do this:
{{shortDescription.description}}
And it return the error bellow:
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
So I try this:
{{shortDescription | debug}}
debug is a special pipe that I create to ensure that it returns value, and It return the value bellow:
"shortDescription": {
"video": {
"url": ""
},
"text": {
"description": "<strong>Lorem</strong>ipsum",
"goTo": "le concept"
}
}
But if I try to use description
property or goTo
property, it returns the error I mentionned before.
And do not understand what happen with this?
All helps are welcomed!
Upvotes: 1
Views: 137
Reputation: 214165
Since you're getting data asynchronously at first time your variable shortDescription
equals undefined
.
Elvis operator should resolve your issue:
{{shortDescription?.description}}
Other options:
1) use structural directive ngIf:
<template *ngIf="shortDescription">
{{shortDescription.description}}
</template>
2) set initial value
export class HomeComponent implements AfterViewInit, OnInit {
private shortDescription = { description: '' };
...
Upvotes: 2