I'm having real trouble wrapping my head around observables and subscriptions in angular2. The problem I am currently having is the following:
I have a service which contains methods to post and get data from an API. The service is injected into a component, which directly calls those methods in the service. The service then retrieves data and stores it itself, but I then want to process that data within the component. I cannot work out how to have the component execute a function after the service has retrieved and stored the data itself.
service.ts
import { Injectable } from 'angular2/core';
import { Http } from 'angular2/router';
@Injectable()
export class Service {
result: Object;
constructor(http: Http) {
this.http = http;
}
httpGet(url) {
return this.http.get(url).subscribe(
result => this.result = result.json(),
error => console.log(error),
() => {}
)
}
}
component.ts
import { Component } from 'angular2/core';
import { Service } from './service';
@Component({
...
})
export class Component {
formattedResult: Object;
constructor(service: Service) {
this.service = service;
this.service.httpGet('/api')
// How do I call format result on service.result only after it is completed?
this.formatResult(service.result) // Need to execute this after the http call is completed
// I want something like:
this.service.httpGet('/api').then(() => formatResult(this.service.result));
}
formatResult(result) {
this.formattedResult = result.map(x => x.length) // For example
}
}