1
votes

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?

2
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

2 Answers

0
votes

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!')
    );
}
1
votes

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')))