Search code examples
angulartypescriptionic-frameworkionic4

Type 'Subscription' is not assignable


Hello the code below performs a rest call to an endpoint on node.js backend in this ionic app however when I run the code it returns me the following error how can I fix this?

Error:

ERROR in src/app/services/user.service.ts(22,5): error TS2322: Type 'Subscription' is not assignable to type 'Observable<any>'.
[ng]   Property '_isScalar' is missing in type 'Subscription'

TypeScript Code:

 //Metodo che esegue il login dell'utente
  loginService(username: string, password: string):Observable<any>
  { 
    return this.http.post(url+"/login",{"Username": username,"Password": password}).subscribe((val) => {console.log("POST call successful value returned in body",val);}, response => {  console.log("POST call in error", response); }, () => { console.log("The POST observable is now completed."); });
  }

Solution

  • Well, the error message is clear enough: you declare an observable, but return a subscription. You should simply do

    loginService (Username: string, Password: string): Observable<any> { 
        return this.http.post(url + "/login", { Username, Password });
    }
    

    If you want your loginService do do some postprocessing of the results, you should use some RxJS operators in the pipe. Something like

    return this.http.post(/* args */).pipe(
        tap(val => console.log('Success message. ', val),
        catchError(err => {
            console.error('Error message. ', err);
            return throwError(err);
        }))