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?

2
  • 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 ¯_(ツ)_/¯ Commented Apr 24, 2016 at 18:10
  • @tibs I completely agree it sounds silly. Unfortunately I'm not really sure how to describe what I'm looking for. Commented Apr 24, 2016 at 18:23

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

6 Comments

That this.somevalue.next is new. How does that work? And what is BehaviorSubject, where does it come from?
Does this not introduce overhead; it seems like more work is done?
This is very cheap in relation to for example a DOM manipulation or even a server call.
So does this solve the problem I think I'm having; is it a good practice?
Basically yes. It might vary slightly depending on the actual use case. See also stackoverflow.com/a/36291681/217408
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.