Gregg Gregg - 6 months ago 16
AngularJS Question

Success / Error Reporting from Service with Events / Observables

Using some documentation I found online, I've written a service method for saving some data like this:

@Injectable
export class BrandService {

brands$: Observable<Brand[]>;
private _brandsObserver: Observer<Brand[]>;
private _dataStore: {
brands: Brand[]
};

constructor(private http: Http) {
this.brands$ = new Observable(observer => this._brandsObserver = observer).share();
this._dataStore = { brands: []};
}

saveBrand(brand: Brand) {
var headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post("http://localhost:8080/api/brands", JSON.stringify(brand), { headers: headers })
.map( (response: Response) => response.json()).subscribe(
data => {
this._dataStore.brands.push(data);
this._brandsObserver.next(this._dataStore.brands);
},
error => console.log("Could not create Brand"));
}
}


What this allows me to do is push updates to my collection of Brands and my table on the view will observe these changes and update automatically so I don't have to manually refresh it. All is well with the world.

My problem is that since I'm subscribing to the
http.post
in the service, my component now has no way of knowing whether or not this call succeeded, which also means that, since I'm showing the form in a modal dialog, I don't know if I should close the dialog or display errors. My component simply does this...

this._brandService.saveBrand(this.brandForm.value);


So, I was thinking that I should figure out a way to a) fire an event in the service that I'm listening for in the component for when good / bad things happen and act accordingly, or b) figure out some way of observing some other properties in the service that I can act on when those changes are detected. But I'm pretty new to all this observable stuff and I don't really even know where to begin.

data => {
this._dataStore.brands.push(data);
this._brandsObserver.next(this._dataStore.brands);
// fire some success event or
// update some observed property
},
error => {
// fire some failure event or
// update some observed property
}

Answer

You could do the subscribe() at call site

saveBrand(brand: Brand) {
    var headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return this.http.post("http://localhost:8080/api/brands", JSON.stringify(brand), { headers: headers })
       .map( (response: Response) => response.json()).map(
           data => {
             this._dataStore.brands.push(data);
             this._brandsObserver.next(this._dataStore.brands);
           });
  }
this._brandService.saveBrand(this.brandForm.value)
.subscribe(
    value => onSuccess(),
    error => onError());

If you still want to do some generic error handling in saveBrand you can use the catch operator (like used in Intercepting errors and subscribing to)