Observable result constructor not called

时间:2017-03-22 18:39:00

标签: javascript angular typescript

I am trying to run some code everytime a observable has a result type of MessageResult

Calling the service

this.campaignService.postCreate(this.authService, {
            CampaignCode: this.campaignCode,
            Year: this.year,
            StartDt: this.startDt,
            EndDt: this.endDt,
            InhouseDt: this.inhouseDt,
            MailDt: this.mailDt,
            MarketingId: this.marketingId,
            TemplateId: this.templateId
        }).subscribe(x => {
           console.log(x.text);
           //this doesn't event work -> x.fire; or x.fire();
});

Then the service

  postCreate(refAuthService, formResult: any): Observable<MessageResult> {
    return refAuthService.PostWithHeader("http://api.positive.local:38880/api/campaign/postcreate", formResult)
        .map(this.extractData).catch(this.handleError);
}

The messageResult

import { ToastsManager } from 'ng2-toastr/ng2-toastr';
import { OnInit } from '@angular/core';

export class MessageResult {
    constructor(
        public text: string,
        public type: string,
        public title: string,
        private toastr: ToastsManager) {
        this.fire();
    }

    fire() {
        console.log("that");
        if (this.type == 'error')
            this.toastr.error(this.text, this.title, {
                toastLife: 2500
            });
        else if (this.type == 'success')
            this.toastr.success(this.text, this.title, {
                toastLife: 2500
            });
    }

    ngOnInit() {
        console.log("this");
    }

}

Neither this nor that was shown in the console.

The goal is to have every observable result that is a MessageResult to fire the message without additional coding.

1 个答案:

答案 0 :(得分:0)

一个想法是尝试将fire()函数移动到服务,并让它采用MessageResult类型的参数,并向您的observable添加另一个map函数:

postCreate(refAuthService, formResult: any): Observable<MessageResult> {
    return refAuthService.PostWithHeader("http://api.positive.local:38880/api/campaign/postcreate", formResult)
        .map(this.extractData)
        .map(data => this.fire(data)   //<-- ADD THIS
        .catch(this.handleError);
}

这样,fire函数将在订阅observable时触发,并且在使用该服务的组件中不需要额外的编码。

通常,我使用接口来映射来自observable而不是类的数据,尽管类可以正常工作。但我将任何逻辑都局限于组件而不是数据模型。