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

Limiting the character input in ion-textarea within Ionic 2: A step-by-step guide

In my Ionic 2 application, I need to limit user comments to less than 500 characters in a text area. What is the best way to implement this restriction? ...

Uniform retrieval function for interaction with API

I have developed my server backend using PHP and now I am looking to establish communication between the frontend (typescript) and backend. For each of my API requests, I desire to receive a standardized response. Hence, every response from the server fol ...

Converting constants into JavaScript code

I've been diving into typescript recently and came across a simple code snippet that defines a constant variable and logs it to the console. const versionNuber : number = 1.3; console.log(versionNuber); Upon running the tsc command on the file, I no ...

Generating interactive forms in Angular 7 using API data

I have developed a component that generates dynamic forms using angular reactive forms. When I attempt to utilize this component to create form fields in another component based on the response from my API, the form appears disabled and I am unable to make ...

Conceal a table if it has no content

I am dealing with 2 tables that contain various data sets. img01 If both of my tables happen to be empty, I would prefer them to be hidden. img02 Is it feasible to implement this in Angular? If you have a solution for me, I would be eager to give it a ...

An error encountered while trying to utilize the npm convert-units package within an Ionic 4 application

In my Ionic 4 app, I am utilizing version 2.3.4 of the npm package called convert-units. To install this package in my Ionic 4 application, I used the CLI command: npm i convert-units --save However, upon importing the library with import { convert } fro ...

Encountered a style group error 'non-collision' while using Angular with HERE Maps JS API 3.1

Occasionally, I encounter an error when trying to load a HERE map with the satellite base layer: Tangram [error]: Error for style group 'non-collision' for tile 13/16/15542/12554/15 Cannot read property 'retain' of undefined: TypeE ...

Searching through an array of objects with ng2-completer does not yield any search results

Having some trouble with the ng2-completer plugin when trying to enable auto-complete functionality in a search box. The issue arises when attempting to use an array of objects instead of just strings, resulting in a 'No Results found' message. E ...

Ways to determine the current active tab in React are:

Currently, I am facing an issue with my code involving two tabs. Upon clicking on the second tab, I want to display a specific message. However, I am struggling to determine when the second tab is selected. The main problem lies in the fact that the selec ...

Using Angular 2 to toggle visibility based on a select box's value

<div class="form-group"> <label class="col-md-4 control-label" for="is_present">Is Present?</label> <div class="col-md-4"> <select id="is_present" name="is_present" class="form-control" *ngIf="candidates.is_present === tr ...

Troubleshooting ng module not found error when deploying Typescript + Angular app on Azure App Service using Azure DevOps pipeline

My Typescript and Angular application runs perfectly when tested locally. Now, I'm in the process of setting up a deployment pipeline using Azure DevOps to build and release it to an App Service running on Linux (Node.js web app). Although the pipel ...

Can you explain how to incorporate global functions from a javascript library into an Angular 2 project?

Recently I started working with angular-cli and came across a situation where I have an index.html containing a javascript script with some global functions. I want to access these functions in multiple parts of my application. As someone who is new to A ...

utilize a document within ngx Translate

I've been working on transitioning an app from AngularJS to Angular 4. As I gradually move components over, I'm encountering issues with translation. My goal is to continue using the old AngularJS translation alongside ngx-translate. Prior to ...

The predeploy function encountered an error: Command ended with a non-zero exit code of 2 due to an "import issue"

Currently, I am in the process of learning how to utilize Cloud Functions for Firebase with TypeScript. Unfortunately, I have hit a bump in the road when attempting to deploy Firebase. If you take a look at Vscode, you'll see what I mean: The error m ...

I'm facing challenges in getting my server action to trigger. The error message that keeps popping up is unexpected submission of a React form

I have been working on developing a registration form using Next.js, react-hook-form, and Zod. Here is the code snippet for the form component: 'use client'; import { z } from "zod"; import { useRef } from "react"; import { u ...

The Angular Material table does not adapt to different screen sizes

I developed an Angular application using Angular Material that features a table with 22 columns. However, when I expand the browser window, some columns are hidden. Additionally, on mobile browsers, not all columns are displayed. I have attempted the follo ...

Error occurs when using JSON.stringify with a Typescript array map

When running this code snippet in Typescript: [].map(JSON.stringify); An error is being thrown: Argument of type '{ (value: any, replacer?: ((key: string, value: any) => any) | undefined, space?: string | number | undefined): string; (value: a ...

Unique TypeScript code snippets tailored for VSCode

Is it possible to create detailed custom user snippets in VS Code for TypeScript functions such as: someArray.forEach((val: getTypeFromArrayOnTheFly){ } I was able to create a simple snippet, but I am unsure how to make it appear after typing an array na ...

The functionality of React useState seems to be operational for one state, but not for the other

I am currently working on developing a wordle-style game using react. Within my main component, I have implemented a useEffect that executes once to handle initialization tasks and set up a "keydown" event listener. useEffect(() => { //The getWor ...

Typescript: The type 'Observable<{}>' cannot be assigned to the type 'Observable'

I'm encountering an issue with the Observable type, any thoughts on how to resolve it? import { PostModel } from '../model/postModel'; import { Subject } from 'rxjs/Subject'; import { Observable } from 'rxjs/Observable&ap ...