我正在使用服务提出请求。
主页.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;
}
}
我将此服务用于主页组件
主页.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
属性,它会返回我之前提到的错误。
并且不明白这会发生什么?
欢迎所有帮助!