0

Unfortunately as I was storing many results on the service, I'm now stuck with many {{myservice.somevalue}} (and myservice.someother) etc. sprinkled over my other components.

I believe it would be nicer to return from the service to a component.

This is the code that I have on the service:

getIssue(issueName: string) {
    return this.http.post(this.URL + 'issue/all', JSON.stringify({'issueName': issueName}))
                    .subscribe(data => this.somevalue = data.json(),
                                err => console.log(err));
}

So then on several other components I call functions like this.myservice.getIssue(issueName).

In the HTML I'd prefer to use {{somevalue}}.

What can I do to return a http observable from the http service?

PascalVKooten
  • 20,643
  • 17
  • 103
  • 160
  • It's kinda unclear what do you want to do ? **return this.http.post(....)** is already an **Observable**. So you do return an Observable from the http service ¯\_(ツ)_/¯ – Tiberiu Popescu Apr 24 '16 at 18:10
  • @tibs I completely agree it sounds silly. Unfortunately I'm not really sure how to describe what I'm looking for. – PascalVKooten Apr 24 '16 at 18:23

1 Answers1

1
class SomeService {
  someValue = new BehaviorSubject();

  getIssue(issueName: string) {
      return this.http.post(this.URL + 'issue/all', JSON.stringify({'issueName': issueName}))
                      .subscribe(data => this.somevalue.next(data.json()),
                                  err => console.log(err));
  }
}

In your component

class MyComponent {
  constructor(someService:SomeService) {
    someService.someValue.subscribe(val => {
      this.someValue = val;
    });
  }
}

For an alternative approach see also https://stackoverflow.com/a/36291681/217408

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567