Angular 2:使用Observable并返回Observable

时间:2017-03-23 13:50:46

标签: angular observable

我对angular2和observables有疑问。 在服务中,我想使用observable(从另一个服务加载),然后将数据作为可观察对象返回。

我该怎么做? 我有这段代码:

getEPGDayByChannel(channelID, newDate) {
        let mydate = new Date(newDate.getFullYear(), newDate.getMonth(), newDate.getDate(), 0, 0, 0);


            let fromDate = new Date(mydate.getFullYear(), mydate.getMonth(), mydate.getDate(), 0, 0, 0);
            let endDate = new Date(mydate.getFullYear(), mydate.getMonth(), mydate.getDate(), 23, 59, 59);
            this.apiService.getChannelEPGbyTime(channelID, fromDate, endDate).
            subscribe(
            data => {
                //do some magic with the data
                // return some thing of the data as an observable
                return Observable.of(data.programme);
            },
            error => { this.variables.setFailure(error);}
            );

     }

但是使用这段代码我会失败:

EXCEPTION: Uncaught (in promise): TypeError: this.epgService.getEPGDayByChannel(...) is undefined

Unhandled Promise rejection: this.epgService.getEPGDayByChannel(...) is undefined ; Zone: angular ; Task: Promise.then ; Value: TypeError: this.epgService.getEPGDayByChannel(...) is undefined

我会很高兴得到一些帮助!

1 个答案:

答案 0 :(得分:2)

试试这个:

getEPGDayByChannel(channelID, newDate) {
    let mydate = new Date(newDate.getFullYear(), newDate.getMonth(), newDate.getDate(), 0, 0, 0);


    let fromDate = new Date(mydate.getFullYear(), mydate.getMonth(), mydate.getDate(), 0, 0, 0);
    let endDate = new Date(mydate.getFullYear(), mydate.getMonth(), mydate.getDate(), 23, 59, 59);

    return this.apiService.getChannelEPGbyTime(channelID, fromDate, endDate)
        .map(data => {
            //do some magic with the data
            // return some thing of the data as an observable
            return data.programme;
        })
        .catch(error => { 
            this.variables.setFailure(error);
        });

 }