The Angular4 HttpClient is throwing an error stating that the type 'Observable<Observable<Object>>' cannot be assigned to the type 'Observable<boolean>'

Currently, I am utilizing the Angular 4 http client to fetch data from the server, but I am encountering an error that states:

Type 'Observable<Observable<Object>>' is not assignable to type 
  'Observable<boolean>'.

Within the http request, my code looks like this:

  saveCredit(data): Observable<boolean> {

   return this._http.post(this.authurl + 'auth/save-credit', data)
     .map((res) => {
    return Observable.of(res);
      }, (err) => {
       return Observable.of(false)
     });
  }

After saving on the server, I am returning either true or false. What additional steps should I take in order to effectively utilize the above method using:

this._acceeService.saveCredit(data).subscribe((res)=>{
   ...do my stuff here
})

Answer №1

By using the this._http.post() method, you are already working with an observable. Therefore, in order to return an observable of boolean values within this function, you should return a boolean value.</p>

<p>One possible approach is the following:</p>

<pre><code>saveCreditData(data): Observable<boolean> {
    return this._http.post(this.authurl + 'auth/save-credit', data).map(
        res => !!res,
        err => false
    );
}

Answer №2

A common mistake is returning an observable inside another observable.

Instead of nesting observables, it's recommended to just return the initial observable and utilize the catch operator for error handling.

saveCredit(data): Observable<boolean> {
   return this._http.post(this.authurl + 'auth/save-credit', data).catch(this.handleError)  
}  

public handleError = (error: Response) => {            
    // Handle messaging and errors here
    return Observable.throw(error)
}

Alternatively, if you need to use an Observable within another, consider using the flatMap Operator

this._acceeService.saveCredit(data)
.flatMap(res=>res)
.subscribe((res)=>{
   ...perform actions here
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leverage ng2-charts along with a loading component during the AfterViewInit lifecycle hook

Currently, I am working on a web page that contains various charts. My focus right now is on developing a simple loader as shown below: <div *ngIf="loading === true; else elseBlock" class="container"> <div class="grid-pulse la-3x"> </di ...

Errors encountered during the Angular project build

I need help figuring out what's happening. I keep getting the same error while trying to build my project. I've already attempted deleting typings, angular directory, and performing typings install but nothing seems to be working. All the necess ...

Tips for extracting key values from an array of objects in Typescript

I am working with an array called studyTypes: const studyTypes = [ { value: "ENG", label: "ENG-RU", }, { value: "RU", label: "RU-ENG", }, ]; Additionally, I have a state variable set ...

What is the process of mapping an array of elements for a React component using TypeScript?

Check out my unique component: import React, { FunctionComponent as FC } from 'react'; type shapeMidNumbersInput = { arrMidNumbers: Array<number> }; const MidNumbers: FC<shapeMidNumbersInput> = ({ arrMidNumbers }): Array<Element ...

Determining the instance type of a TypeScript singleton class

I have a unique singleton implementation: class UniqueSingleton { private static instance: UniqueSingleton; private constructor() { // Only allows instantiation within the class } public static getInstance(): UniqueSingleton { if (!Unique ...

Tips for formatting nested Angular components in a visually pleasing manner:

Seeking guidance on the best approach for the following scenario: I have an angular component positioned at a specific route. Let's say the route is: /main-page Currently, the template spans the full width of the screen at this route. I want to add ...

What strategies work well when it comes to developing translation files in Angular?

Currently, I am involved in a front-end project using Angular. For translation implementation, I am looking for the most effective approach to creating translation files. Instead of having a file per language, I am considering creating a translation file f ...

I am encountering difficulties while attempting to import Typescript files. Upon compiling them into Javascript, I am faced with errors in the web browser, specifically the issue of "exports is not defined"

When I run TodoAppUI.js:15, I get an error saying "Uncaught ReferenceError: exports is not defined" In all my classes, I use the export keyword. For example: export class mysclass { public constructor(){} } Even though I have the proper syntax for impo ...

`Toggle your material to reveal the hidden button or content`

As a newcomer to Angular, I am working on developing a website that needs to compile test questions entered in LaTeX format, along with the ability to upload images, gifs, audio, video, and hybrid files from the user's device. Struggling to find a sui ...

What is the best way to initiate multiple processes in Node.js and ensure they finish before proceeding?

When working with Node.js and TypeScript, my goal is to initiate multiple processes using the spawn function. Afterwards, I aim to ensure all of these processes are completed before proceeding to execute any additional commands. ...

Unexpected behavior encountered when running Angular 8 radio button checked function

I have an Angular 8 web app with some unique logic implemented as shown below: HTML: <div *ngFor="let item of selectedItems;"> <input type="radio" [(ngModel)]="mySelectedItem" [value]="item.key" (ngModelChange)="setCh ...

Mastering Typecasting in TypeScript: A comprehensive guide

I have a loadMore function that retrieves data and returns a Promise of either Project[] or Folder[] or undefined. const items = await loadMore(); How can I specifically cast the type of 'items' to Folder[] in TypeScript? ...

Designing the Firebase Structure of an Angular Application

What is the best way to structure Firestore and Angular for efficient querying? When using a JSON Cloud Firestore database, one of the challenges is inserting people and relating them to users. To optimize query speed and efficiency, it is important to c ...

Encountering 'npm install' error while trying to follow the Angular2 5 minute

I encountered an error while attempting to follow the Angular2 5 min quick start guide. Can someone assist me in resolving it? vagrant@vagrant-ubuntu-trusty-64:/vagrant/angular2-tutorial$ sudo npm install <a href="/cdn-cgi/l/email-protection" class=" ...

The HTTP request fails to accept the input value provided

Visual Representation of File Structure https://i.sstatic.net/6nscS.png export class FaqService { public inputValue; constructor(private http: Http) {} ngOnInit() {} setData(val) { this.inputValue = val; console.log(this.inputValue); } getData() ...

The 'connectedCallback' property is not found in the 'HTMLElement' type

After taking a break from my project for a year, I came back to find that certain code which used to work is now causing issues: interface HTMLElement { attributeChangedCallback(attributeName: string, oldValue: string, newValue: string): void; con ...

The Angular Material datepicker seems to be ignoring the limitations set by [min] and [max] restrictions

I have set up a material date picker control named dob as shown below. However, I am facing an issue where the [min] and [max] values set in the HTML are not functioning correctly. The dob control is being validated as soon as the first digit of the date i ...

What is the best way to find a partial string match within an array of objects when using Jest?

I am currently utilizing the following versions: Node.js: 9.8.0 Jest: 22.4.2 A function called myFunction is returning an array structured like this: [ ... { id: 00000000, path: "www.someUrl.com/some/path/to" } ... ] I ...

Guide on submitting a form through the Angular 2 HTTP post method with JavaScript

Currently working on grasping the concepts of Angular2, but facing challenges when attempting to utilize http.post() for submitting a form to my Web API. ...

I encountered an error when attempting to utilize a recursive type alias in a generic context

When attempting to use a recursive type alias in a generic function, TypeScript v3.7.5 throws the error message: Type instantiation is excessively deep and possibly infinite.(2589). type State = { head: { title: string; description: s ...