Can the Rxjs library's Observables of() function be used to output multiple values?

I am inquiring about this because I came across in the Angular documentation that of(HEROES) returns an Observable which emits a single value - an array of mock heroes. If I cannot use of(), do you have any alternative suggestions for me?

I am currently working on an Angular 5 project utilizing RxJS with of(), and I am attempting to retrieve two arrays from two different mock files.

To elaborate, I am developing a small application that will showcase NBA Eastern teams contained in mock-nba-est.ts and Western teams in mock-nba-west.ts. The tutorial I am following can be found here: Angular.io services tutorial, in my endeavor to return these teams.

The error I encountered with the current code is as follows:

Failed to compile.

 src/app/nba/nba.component.ts(34,8): error TS2339: Property 'subscribe' does not exist on type 'Nba[]'.

Below is my existing code:

nba.service.ts:

 import { NbaMessageService } from './nba-message.service';

 import { Injectable } from '@angular/core';
 import { Observable } from 'rxjs/Observable';
 import { of } from 'rxjs/observable/of';
 import { Nba } from './nba';
 import { NBAE } from './mock-nba-est';
 import { NBAW } from './mock-nba-west';

@Injectable()
 export class NbaService {

constructor(private nbaMessageService: NbaMessageService) { }

getNba(): Observable<Nba[]> {
   // Todo: send the message _after fetching the heroes
   this.nbaMessageService.add('NbaMessageService: fetched nbae !');
   return of(NBAE && NBAW);
}
 }

nba.component.ts

import { NbaService } from './../nba.service';
import { Component, OnInit } from '@angular/core';
import { Nba } from '../nba';
import { NBAE } from '../mock-nba-est';
import { NBAW } from '../mock-nba-west';

@Component({
 selector: 'app-nba',
 templateUrl: './nba.component.html',
 styleUrls: ['./nba.component.css']
 })
export class NbaComponent implements OnInit {

nbae = NBAE;
nbaw = NBAW;

selectedTeam: Nba;

 constructor(private nbaService: NbaService) { }


 ngOnInit() {
   this.getNba();
 }


 onSelect(nbae: Nba, nbaw: Nba): void {
  this.selectedTeam = nbaw;
   this.selectedTeam = nbae;
 }

getNba(): void {
  this.nbaService.getNba()
   .subscribe(nbae => this.nbae = nbae,
              nbaw => this.nbaw = nbaw);
  }
}

nba.component.html:

<h2>The Eastern conference</h2>
<ul class="teams">
<li *ngFor="let nba of nbae"
[class.selected]="nba === selectedTeam"
 (click)="onSelect(nba)">
  <span class="badge">{{nba.id}}</span> {{nba.name}}
  </li>
</ul>

<h2>The Western conference</h2>
<ul class="teams">
  <li *ngFor="let nba of nbaw"
  [class.selected]="nba === selectedTeam"
  (click)="onSelect(nba)">
    <span class="badge">{{nba.id}}</span> {{nba.name}}
  </li>
 </ul>


 <app-nba-detail [nba]="selectedTeam"></app-nba-detail>

mock-nba-est.ts:

import { Nba } from './nba';

export const NBAE: Nba[] = [
{ id: 1, name: 'Boston Celtics' },
{ id: 2, name: 'Cleveland Cavaliers' },
{ id: 3, name: 'Toronto Raptors' },
{ id: 4, name: 'Milwaukee Bucks' },
{ id: 5, name: 'Indiana Pacers' },
{ id: 6, name: 'Washington Wizards' },
{ id: 7, name: 'Philadelphia 76ers' },
{ id: 8, name: 'Detroit Pistons' },
{ id: 9, name: 'New York Knicks' },
{ id: 10, name: 'Miami Heat' },
{ id: 11, name: 'Brooklin Nets' },
{ id: 12, name: 'Orlando Magic' },
{ id: 13, name: 'Charlotte Hornets' },
{ id: 14, name: 'Chicago Bulls' },
{ id: 15, name: 'Atlanta Hawks' }
 ];

mock-nba-west.ts:

import { Nba } from './nba';

export const NBAW: Nba[] = [
 { id: 16, name: 'Houston Rockets' },
 { id: 17, name: 'Golden State Warriors' },
 { id: 18, name: 'San Antonio Spurs' },
 { id: 19, name: 'Minesota Timberwolves' },
 { id: 20, name: 'Denver Nuggets' },
 { id: 21, name: 'Portland Trail Blazers' },
 { id: 22, name: 'New Orleans Pélicans' },
 { id: 23, name: 'Oklahoma City Thunder' },
 { id: 24, name: 'Utah Jazz' },
 { id: 25, name: 'Los Angeles Clippers' },
 { id: 26, name: 'Los Angeles Lakers' },
 { id: 27, name: 'Sacramento Kings' },
 { id: 28, name: 'Memphis Greezlies' },
 { id: 29, name: 'Phoenix Suns' },
 { id: 30, name: 'Dallas Mavericks' }
 ];

Answer №1

To ensure arrays are kept separate, you can utilize an object:

retrieveNBA(): Observable<{ easternConference: NBA[], westernConference: NBA[] }> {
  // Task: send message _after_fetching the heroes
   this.NBAMessageService.add('NBAMessageService: fetched NBA data!');
   return of({ easternConference: EASTERN_NBA, westernConference: WESTERN_NBA });
  }
 }

In your component:

fetchNBA(): void {
  this.nbaDataService.retrieveNBA()
   .subscribe(data =>  {
     this.easternConference = data.easternConference;
     this.westernConference = data.westernConference;
   });
  }
}

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

Steer clear of chaining multiple subscriptions in RXJS to improve code

I have some code that I am trying to optimize: someService.subscribeToChanges().subscribe(value => { const newValue = someArray.find(val => val.id === value.id) if (newValue) { if (value.status === 'someStatus') { ...

Positioning a Box tag at the bottom using MUI 5

My goal is to position a Box tag at the bottom of the page. Current Behavior: https://i.stack.imgur.com/ZupNo.png I am looking to place a TextField and send button at the bottom of the page on both browser and mobile. I want user messages to be above th ...

What is the best way to determine someone's age using their date of birth in a React

Looking for assistance with calculating a user's age from their date of birth on a registration form. I've tried various versions without success, can you provide some ideas that could be tailored to my project? Thank you. Here is the registratio ...

How to utilize TypeScript fetch in a TypeScript project running on node with Hardhat?

During a test in my hardhat project on VSCode, I encountered the need to retrieve the metadata object of my NFT from a specified URL. Initially, I assumed I would have to import fs to read the URL. However, while typing out the method, I impulsively opted ...

What is the best way to incorporate Redux into your project?

Is it necessary to incorporate Redux for every API call, even when the data is not shared among multiple components? For instance, consider a users-list component that needs to fetch and display the list of users exclusively within its own interface. Is ...

The 'xxx' type does not have an index signature, so the element is implicitly assigned an 'any' type

I'm currently facing an issue with TypeScript. The error message I'm encountering is related to the following section of code: The Interface: export default interface IUser { username: string; email?: string; isActive: boolean; group: s ...

The fixed header option is not available for the CdkVirtualScrollViewport

Looking for a solution in my Angular application where I need to keep the table header at a fixed position while displaying the scrollbar only on the body part. Currently, I am utilizing the CdkVirtualScrollViewport library in Angular to render the table c ...

Refresh Form (Reactive Forms)

This is the HTML code snippet: <div class="container"> <ng-template [ngIf]="userIsAuthenticated"> <form [formGroup]='form' name="test"> <div class="form-group"> <input type="text" class="form-contr ...

npm run start is functioning correctly while ng serve is experiencing issues

I attempted to launch an angular 2 application with ng serve on my Linux machine, but encountered issues. However, using the npm run start command worked perfectly fine for me. Upon running ng serve, I received the following message: As a forewarning, we ...

Issue encountered: `property does not exist on type` despite its existence in reality

Encountering an issue in the build process on Vercel with product being passed into CartItem.tsx, despite being declared in types.tsx. The error message reads: Type error: Property 'imageUrl' does not exist on type 'Product'. 43 | ...

Angular - Using the 'name' attribute with the 'mat-select' element

Currently, I am working on an Angular form that involves the dynamic nature of the userEntitiesRoles array. To ensure smooth functionality, each mat-select tag within the ngFor loop requires a unique name attribute. In order to achieve this, I attempted to ...

Is there a way to determine the port being used by the http-server?

After using the command prompt to install the HTTP server with npm install http-server -g, I received a relevant path but no port number. How can I determine what the port number is? http://localhost:8080/index.html I encountered an error on IIS 8.5. ...

What is the most efficient way to incorporate Google Analytics code into the header tag of index.html?

If I were to receive the complete Google Analytics code from BE, what would be the most effective method of incorporating it into the index.html file? Just looking for a simple setup of GA. ...

Enhancing MUI themes by incorporating module augmentation for multiple typings

I am looking to create a repository with two directories, each using MUI and TypeScript. Both directories will have their own theme defined in one ThemeProvider per root. In the main index.tsx file in the root directory, I want to specify which component t ...

In Angular, you can easily modify and refresh an array item that is sourced from a JSON file by following these steps

Currently, I am working on implementing an edit functionality that will update the object by adding new data and deleting the old data upon updating. Specifically, I am focusing on editing and updating only the comments$. Although I am able to retrieve th ...

What is the process for loading the chosen option JSON object from an array when a button is clicked?

I have a TypeScript file containing JSON objects that can be selected as options from a dropdown list. I am looking for guidance on how to load/instantiate the selected JSON object when the user clicks a button to proceed. Specifically, I would like to le ...

When using React MUI Autocomplete, make sure to handle the error that occurs when trying to filter options using the

I am trying to implement an autocomplete search bar that makes a custom call to the backend to search through a list of tickers. <Autocomplete multiple id="checkboxes-tags-demo" options={watchlis ...

Angular 2: Issue with view not reflecting changes in array

I am working on a component that involves two arrays: arrayA and arrayB. The elements in arrayB are filtered from arrayA. In the template, I have: <div *ngFor="let elem of arrayB">{{elem.something}}</div> There is also a button: <button ( ...

When using Angular9 with PrimeNG fullcalendar, it may encounter issues such as errors stating "Cannot find namespace 'FullCalendarVDom'." and "Please import the top-level fullcalendar lib"

Using primeng p-fullcalendar in my angular application. Encountering an error in the command-line: 'Cannot find namespace 'FullCalendarVDom' Also seeing this error in the browser: 'Please import the top-level fullcalendar lib before a ...

Storing data from a collection of interface objects in a string array

Take a look at the following code snippet: import React, {FC} from 'react'; import {useFetchErrors} from "../Api/Api"; import {useLocation} from "react-router-dom"; interface ExecutionTableProps { project_id: number } const ...