user7753083 user7753083 -4 years ago 124
Javascript Question

Observable result constructor not called

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.

Answer Source

One idea is to try moving the fire() function to the service and have it take a parameter of type MessageResult and add another map function to your observable:

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

This way, the fire function will fire when the observable is subscribed to and does not require additional coding in the component consuming the service.

Generally, I use interfaces to map data from observables instead of classes, though classes can work fine. But I keep any logic confined to a component and not a data model.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download