1

I am having issues getting the data returned from my service.

I'm using Angular 8.

Here is the code:

In the service

callit(url: string) {
    this.subscription = this.socket$.subscribe(
      (message) => {
        return message;
      },
      (err) => {
        return err;
      },
      () => console.warn('Completed!')
    );
}

In the component.

I've tried:

getResultFromService() {
    var res = this.myservice.callit(myurl);
}

The above res says undefined.

I've tried:

getResultFromService() {
    this.myservice.connect(myurl).subscribe
}

But subscribe is giving me this error:

Property 'subscribe' does not exist on type 'void'.ts(2339)

How can I get the result from the service return without using a promise?

Raj Paliwal
  • 943
  • 1
  • 9
  • 22
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – UncleDave Dec 12 '19 at 11:26
  • Don't think this is a direct duplicate, it seems more a question about observables. Re-phrasing the question towards that direction with regards to what your trying to achieve may be better? – ste2425 Dec 12 '19 at 11:38

2 Answers2

1

Your callIt function returns nothing.

So from the outside you cannot call .subscribe as your trying to call it on undefined.

Now within your callIt method your are subscribing to the observable.

If you wish to keep that logic you will be instead returning a subscription which has no .subscribe method. You could move the subscribe logic outside the callIt method and return the observable.

Or you could still return an observable but use pipes to intercept the messages, and still subscribe from the outside. This would allow you to still perform any logic you have within your service.callIt and still subscribe on the outside.


    return this.socket$
        .pipe(tap((message) => console.log(message))
        .pipe(catchError((e) => console.error(e)))
        .pipe(finally(() => console.log('Completed')))
ste2425
  • 4,656
  • 2
  • 22
  • 37
0

Try like this.

.service

callit(url: string) {
    return this.socket$
}

.component

getResultFromService() {
    this.myservice.callit(myurl).subscribe(
      (message) => {
        res = message;
      },
      (err) => {
        console.log('error')
      },
      () => console.warn('Completed!')
    );
}
Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79