Typescript - A function whose declared type is neither 'void' nor 'any' must return a value

Viewed 5937

I'm new of Angular2/Typescript, I'm trying to compile my project but I get this error:

A function whose declared type is neither 'void' nor 'any' must return a value

This is the code:

SyncCustomer(codCli: string): Observable<any>
{ 
    this.mdService.Ordini_Sincronizza(codCli).subscribe(
    data => {          
      return Observable.of(data);
    },
    error => {
      console.log(error);
      return Observable.of(error);
    });  
}

I don't realize where the problem is...

Thanks to support!

UPDATE 001:

I edited the code in this way and now it compiles...

  SyncCustomer(codCli: string): Observable<any> {
    return Observable.of(this.mdService.Ordini_Sincronizza(codCli).subscribe(
      data => {
        return data;
      },
      error => {
        console.log(error);
        return error;
      }));
  }

Does it have sense to return an observable of the subscribe ???

1 Answers

The return data/return error part is only relevant for the two callbacks, your method does not return anything for your first code, and a Subscription for the second one.

If you want to return an Observable, you should not subscribe directly:

SyncCustomer(codCli: string): Observable<any> {
  return Observable.of(this.mdService.Ordini_Sincronizza(codCli);
}

Actually I don't think you need to subscribe here. You need to subscribe in order to get a cold Observable to start emitting, but you should subscribe where you need the data (usually inside your component) or not subscribe at all inside the component code but inside the template using the async pipe.

Related