Unable to fetch the Observable value

I have a function that returns an Observable<Person[]>, where Person is my model:

export interface Person {
  id: string;
  age: number;
}

Now in my component.ts, I am calling this function and aiming to retrieve the array to display it in the HTML.

An example of the array that is returned looks like this:

[{"id":"13434 1","age":21},{"id":"34334 1","age":27}]

I have two buttons that trigger the same function.

In my component.ts, I have three methods that are triggered when these buttons are clicked. I want to set a variable to store the returned value of the Observable within these methods. However, my attempts have been unsuccessful...

These are the functions:

@Injectable()
export class MyCmp implements OnInit {

  listOneData: Observable<Person[]>;
  listTwoData: Observable<Animal[]>;

  showListOne = false;
  showListTwo = false;

  constructor(private _myService: MyService) {
  };

  public showListOneData(): void {
    this.showListOne = true;
    this.showListTwo = false;
    this._myService.getListOneData().subscribe(res => {
      this.listOneData = res;
    })
  }

  public showListTwo(): void {
    this.showListTwo = true;
    this.showListOne = false;
    this._myService.getListTwoData().subscribe(res => {
      this.listTwoData = res;
    })
  }
}

this.listTwoData = res; - This line does not compile because I am assigning Person[] to

listOneData: Observable<Person[]>;
. However, even if I remove the Observable<>, it still does not work.

Can someone please provide an efficient way to achieve this? I do not want to handle it asynchronously as I intend to send an array to the HTML. Also, where should I handle the unsubscribe action in the code?

Thank you very much!

Answer №1

It seems like you have a need for both data from the observable and a subscription object for unsubscribing purposes:

@Injectable()
export class MyCmp implements OnInit {

  listOneData: Person[];
  listTwoData: Animal[];

  listOneSubscription: Subscription;    
  listTwoSubscription: Subscription;

  showListOne = false;
  showListTwo = false;

  constructor(private _myService: MyService) {
  };

  public showListOneData(): void {
    this.listOneSubscription = this._myService.getListOneData().subscribe(res => {
      this.showListOne = true;
      this.showListTwo = false;
      this.listOneData = res;
    })
  }

  public showListTwo(): void {
    this.listTwoSubscription = this._myService.getListTwoData().subscribe(res => {
      this.showListTwo = true;
      this.showListOne = false;
      this.listTwoData = res;
    })
  }
}

If you need to unsubscribe at some point, you can do so like this:

this.listOneSubscription && this.listOneSubscription.unsubscribe();
this.listTwoSubscription && this.listTwoSubscription.unsubscribe();

You mentioned wanting to avoid asynchronous behavior, but note that JavaScript is inherently asynchronous. Consider how you want to handle loading time for the user - perhaps incorporating a progress indicator in your view would be a good approach.

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

Is it possible for the Redux inside a React component from npm to clash with the Redux in the container?

I am looking to bundle a React component with npm and incorporate Redux to handle state within the component. If another React project imports my component, will it cause conflicts with the Redux instance of that project? For example: The component code ...

Issues with AJAX functionality in select fields - LATEST UPDATE

I have created a form with two select fields. The first field is populated with the parents of a custom taxonomy, and the second field is populated with the children of each parent. I used AJAX to accomplish this, but it doesn't seem to be working pro ...

Tips for preventing HTML ID clashes while integrating with the Document Object Model of external websites

When incorporating additional HTML elements into a webpage using Javascript or jQuery, along with external CSS declarations, it is important to avoid conflicts with existing IDs and class names already present on the page. This could lead to issues if ther ...

Executing Laravel Ajax Requests on the whole website

I have been encountering an issue with my Ajax post call in my application. The call is supposed to update the Navigation throughout the entire site, but it seems to be working on some pages and not others. I am looking for a way to fix this and make it mo ...

The initial ajax request may sometimes return as 'undefined' during its first call

I have been working on creating a text input help feature similar to a desktop using the datatable.in table with keyboard navigation. In order to achieve this, I am dynamically changing the data source and also altering the header column. I have been succe ...

Tips for accurately typing a "Type Mapping" function

In my code, I have a specific type designed for a function that takes one type I as input and returns another type O as output. Here is how it currently looks: export interface IFunctionalMapping<I, O, K extends keyof O> { [prop: Extract<O[K], ...

Creating clones of <li> elements using JQuery and appending them to the end of a <ul> list

I have a regular ul li list and I am looking to add an additional li based on the first one in the list. Here is the HTML: <div id="gallery"> <ul> <li>Point Nr 1<p>lol</p></li> <li>Point Nr 2</li> <li> ...

Using the `type=file` input in Internet Explorer 11

Encountering an issue with the input type file on IE11. In IE11, the input field is displayed as two tab-able pseudo elements (text/button). Tried using the class ::-ms-browse to hide the button with display: none, but it remains tab-able. To replicate: ...

Modify the main container width based on the size of the table

Would it be possible for the main container width to increase along with the table width? Is that achievable? <div class="container main-con"> <table class="table table-hover"> <tr><td></td></tr> </table> ...

Injection of Angular state resolve into controller fails to occur

I'm attempting to ensure that the value from ui-router's resolve is successfully passed to the controller portalsForUserCtrl. Take a look at the router code below: (function () { 'use strict'; var myApp = angular.module("myApp", ["co ...

What is the best way to exclude the bottom four rows when sorting with MatSort?

Is there a way for me to keep the last four rows fixed when sorting the table based on the column header? Here is an image of the table: table image <table mat-table [dataSource]="dataSourceMD" matSort (matSortChange)="getRowMaximoTable( ...

What is the best way to position the left sidebar on top of the other components and shift them to the

Currently, I am working on a project to display NBA data fetched from an API. I am aiming to recreate the design showcased here: Dribbble Design My main challenge lies in overlaying the left sidebar onto the main box and shifting the components sligh ...

Totally clueless when it comes to JSON

After diving into tutorials on JSON, the structure and syntax are finally clicking for me. However, I'm currently working on a project that requires a GET, and it seems like JSON could help with this. I've come across comparisons of JSON and AJA ...

Combining cells through the utilization of JavaScript

I've searched for ways to merge cells in a table using JavaScript but haven't been able to find any code that works. Is there a specific approach I can follow to implement cell merging like in MS-WORD tables? Your advice would be greatly apprec ...

Leveraging Cheerio in Node.js to locate a precise value within an option tag

I'm facing difficulties in selecting the exact number (in this case 7) which is the value of the option. This is what I'm attempting: var $ = cheerio.load(html); console.log($('ProductSelect').val($("option:contains('7')").v ...

Best Practices for Implementing Redux Prop Types in Typescript React Components to Eliminate TypeScript Warnings

Suppose you have a React component: interface Chat { someId: string; } export const Chat = (props: Chat) => {} and someId is defined in your mapStateToProps: function mapStateToProps(state: State) { return { someId: state.someId || '' ...

Different ways to showcase a value from the CSS file on the console using console.log

In this guide, you can learn how to create a custom directive in Angular by following this tutorial: Custom Directive Tutorial. The directive should function as intended. Still, I want to see the color value set in the CSS file displayed on the console us ...

What is the best way to prevent the chaining of promises and catches in JavaScript?

I am currently developing an API using node and express to create users. However, I find myself struggling with error handling due to the asynchronous nature of MongoDB functions, which makes me feel like I'm trapped in a "promise hell." I anticipate ...

Encountering a react error following the installation of FontAwesome via npm

I successfully installed fontawesome by visiting their official website and following the steps below: 1. npm i --save @fortawesome/fontawesome-svg-core 2. npm install --save @fortawesome/free-solid-svg-icons 3. npm install --save @fortawesome/react-fon ...

Leveraging the power of a JavaScript framework within the script tag

Hello there! I'm just starting out with vue.js and exploring different JavaScript frameworks. Recently, I came across an interesting example based on the documentation. import modal from 'vue-semantic-modal' export default { components ...