No data received after attempting to retrieve simulated information from the Service

In order to retrieve and showcase data from an Array of Objects, I have set up parameterized routes.

1. app-routing.module.ts

const routes: Routes = [
  {
    path: 'all-trades',
    component: AllTradesComponent,

  }, 
  { 
    path: 'crop/:name', component: CropComponent 

}]

2. Crop.ts

export class Crop {
    name: string;
    checked: boolean;
    subCategory: Subcategory[];
}

export class Subcategory {
    id: number;
    name: string;
    isActive: boolean;
}

3. CropData.ts

I have an Array of objects where I need to access the subCategory and display the name on the webpage. For instance: Clicking on Rice should yield results like 'Basmati', 'Ammamore', OR Clicking on Wheat should show results like 'Durum', 'Emmer', OR Clicking on Barley should provide results as 'Hulless Barley', 'Barley Flakes'

import { Crop } from './Crop';

export const CROP: Crop[] = [
    {
        name: 'Rice',
        checked: true,
        subCategory: [
            {
                id: 1,
                name: 'Basmati',
                isActive: true,
            },
            {
                id: 2,
                name: 'Ammamore',
                isActive: true,
            },
        ],
    },
    {
        name: 'Wheat',
        checked: true,
        subCategory: [
            {
                id: 1,
                name: 'Durum',
                isActive: true,
            },
            {
                id: 2,
                name: 'Emmer',
                isActive: true,
            },
        ],
    }, {
        name: 'Barley',
        checked: true,
        subCategory: [
            {
                id: 1,
                name: 'Hulless Barley',
                isActive: true,
            },
            {
                id: 2,
                name: 'Barley Flakes',
                isActive: true,
            },
        ],
    }
]

4.1 crop.service.ts // Initially attempted this logic

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { skipWhile } from 'rxjs/operators';
import { Crop } from '../shared/Crop';
import { CROP } from '../shared/cropdata';

@Injectable({
  providedIn: 'root'
})
export class CropService {

  constructor() { }

  CropData: Crop
  getCrop(name: string): Crop {
    return this.CropData.filter((crop) => (crop.name === name))[0];


  }
}

4.2 crop.service.ts // Attempted another logic afterwards

export class CropService {
private selectedCrop= new BehaviorSubject<Crop>(null);

setCrop(crop:Crop){
 this.selectedCrop.next(crop);
 }

getCrop(){
this.selectedCrop.asObservable().pipe(skipWhile(val=> val === null)); 
}
}

Encountered issues with both approaches.

5.1 all-trades.components.ts

// Implemented a function initially

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Crop } from 'src/app/shared/Crop';
import { CropService } from '../crop.service';

@Component({
  selector: 'app-all-trades',
  templateUrl: './all-trades.component.html',
  styleUrls: ['./all-trades.component.css'],
})
export class AllTradesComponent implements OnInit {
 
  constructor(private service: CropService, private router: Router) { }

// Attempted to utilize a function but did not obtain desired outcome

onSelect(selectedCrop:Crop){
this.service.setCrop(selectedCrop);
this.router.navigateByUrl(`crop/${crop.name}`);
}


  onChange(event, index, item) {
    item.checked = !item.checked;
    console.log(index, event, item);
  }



  ngOnInit(): void { }

  
}

5.1 all-trades-component.html

<app-header></app-header>
<div
  fxLayout="row"
  fxLayout.lt-md="column"
  fxLayoutAlign="space-between start"
  fxLayoutAlign.lt-md="start stretch"
>
  <div class="container-outer" fxFlex="20">
    <div class="filters">
      <section class="example-section">
        <span class="example-list-section">
          <h1>Select Crop</h1>
        </span>
        <span class="example-list-section">
          <ul>
            <li *ngFor="let crop of crops">
              <mat-checkbox
                [checked]="crop.checked"
                (change)="onChange($event, i, crop)"
              >
                {{ crop.name }}
              </mat-checkbox>
            </li>
          </ul>
        </span>
      </section>

      
  <div class="content container-outer" fxFlex="80">
    <mat-card
      class="crop-card"
      style="min-width: 17%"
      *ngFor="let crop of crops"
      [hidden]="!crop.checked"
    >
   
<!-- here i call the function -->
        <a (click)="onSelect(crop)" routerLinkActive="router-link-active"> 
        <mat-card-header>
          <img
            mat-card-avatar
            class="example-header-image"
            src="/assets/icons/crops/{{ crop.name }}.PNG"
            alt="crop-image"
          />
          <mat-card-title>{{ crop.name }}</mat-card-title>
          <mat-card-subtitle>100 Kgs</mat-card-subtitle>
        </mat-card-header>
      </a>
      <mat-card-content>
        <p>PRICE</p>
      </mat-card-content>
    </mat-card>
  </div>
</div>

<app-footer></app-footer>

  1. crop-componet.ts
import { Component, OnInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { Crop } from 'src/app/shared/Crop';

@Component({
  selector: 'app-crop',
  templateUrl: './crop.component.html',
  styleUrls: ['./crop.component.css']
})
export class CropComponent implements OnInit {
  service: any;
  crop: any;
  route: any;
  cropservice: any;
  sub: Subscription;
  constructor() { }

  ngOnInit(): void {
    // let name = this.route.snapshot.params['name'];
    // this.crop = this.cropservice.getCrop(name);
    this.sub = this.route.paramMap.subscribe(params => {
      let name = params.get("name")
      this.crop = this.cropservice.getCrop(name)
    })
  }

}

7. crop-component.html

<div *ngFor="let category of crop.subCategory">{{category.id}}</div>

This constitutes my entire codebase, and I am facing challenges in fetching data from arrays of objects. If you could provide assistance in resolving this issue, it would be greatly appreciated.

This is how my all-trades.component.html is displayed
  1. Upon clicking on Rice, the output changes as follows (URL gets updated)

[![View Image][1]][1]

  1. When selecting Wheat, the output is as shown below

[![View Image][2]][2]

And so forth... My goal is simply to exhibit the names of the subCategory Array. I await your solution eagerly. [1]: Image 1 [2]: Image 2 [3]: Image 3

Answer №1

It appears that in your version 4.1, you may have overlooked assigning your mock data to the variable.

....

import { CROP } from '../shared/cropdata';


@Injectable({
  providedIn: 'root'
})
export class CropService {

  constructor() { }

  CropData: Crop[] = CROP;        // Don't forget to assign the value


  getCrop(name: string): Crop {
    return this.CropData.filter((crop) => (crop.name === name))[0];
  }
}

In version 4.2, the oversight of not assigning the mock data to the BehaviorSubject is evident. It is crucial for BehaviorSubjects to emit initial data.

...

import { CROP } from '../shared/cropdata';

export class CropService {

private selectedCrop = new BehaviorSubject<Crop[]>(CROP);   // Make sure to pass CROP mock data

    setCrop(crop: Crop[]) {
      this.selectedCrop.next(crop);
    }

    getCrop() {
      this.selectedCrop.asObservable().pipe(skipWhile(val=> val === null)); 
    }

}

A demonstration has been created on Stackblitz Demo for your convenience. Check the console for the output.

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

Using setState as a parameter in a personalized hook in React/Next.js while incorporating TypeScript

I encountered an issue with the following code snippet: import { useState, useEffect } from "react"; type Props = { setState: (value: string) => void; }; const useSomeCustomHook = ({ setState }: Props) => { useEffect(() => { se ...

Identify data points on the line chart that fall outside the specified range with ng2-charts

I'm struggling to figure out how to highlight specific points on a line chart that fall outside a certain range. For instance, if the blood sugar level is below 120, I want to display that point as an orange dot. If it's above 180, I want to show ...

Using jQuery Ajax and PHP for Secure User Authentication

Hello everyone, I could really use some assistance right now. The issue I'm facing is that the error div is not showing the content I expect in the success function of my AJAX request. I've tried alerting the response, which returns true if the ...

Are there any substitute proxy servers that are capable of bypassing CORS restrictions using local IP addresses?

Successfully bypassing CORS for AJAX requests to public IP addresses using proxy servers has been a game-changer. Is there a similar approach that can be utilized for local IP addresses when the server is hosted off-site? Unfortunately, I lack the abilit ...

A more effective strategy for avoiding the use of directives or jQuery in AngularJS

I need guidance on using Angular directives, especially when deciding between JQuery and Angular 1 directives for a particular scenario. Here is an example of my object list: [ { "id":"sdf34fsf345gdfg", "name":"samson", "phone":"9876543210", ...

Unable to generate a search query for the attribute because the query selector has not been specified

Currently facing an issue with a component in Angular 2 that comprises of other components. The components within the 'main' component can appear multiple times in the hierarchy. However, I encountered the following error: "Can't create a q ...

Unraveling Complex Data and Generating Distinct Identifiers with Vue

After reading about normalizing complex data, I am facing a challenge with creating new objects and accessing them by their unique IDs in a component that is generated on the click of a button. I need to be able to assign these new objects to my parent obj ...

Retrieve all users along with their respective posts, ensuring that each post is also accompanied by its corresponding comments in

In my Laravel project, I have set up Eloquent models for User, Post, and Comment. The relationships are as follows: User model public function posts(){ return $this->hasMany('App\Post'); } public function comments(){ return $t ...

An unknown error has arisen: "The page https://registry.yarnpkg.com/react-native-template-react-native-template-typescript cannot be located."

Once I uninstalled the react-native-cli, I attempted to start a React Native project with a typescript template using the following command: npx react-native init MyApp --template react-native-template-typescript However, I encountered an error message: ...

"Unraveling the Mystery of Node.JS: Exploring the Unpredictable Ordering of Nested Promise Thens

It is essential for each download and getFiles call to run separately due to Firebase's potential limitation in handling excessive connections. const bucket = storage.bucket(bucketName); // firebase storage bucket var queue = Promise.resolve(); webs ...

Bootstrap wysiwyg5 editor validation: Ensuring accuracy in your content creation

Currently, I have integrated the Bootstrap wysiwyg5 editor into a form. One of the fields in this form, specifically the text area, is mandatory and cannot be left empty. I am facing a challenge in validating whether the user has entered any content into t ...

Creating a progress bar feature using local storage in JavaScript

Is there a way to retain the progress of the countdown timer with a progress bar on page reload? Here is an example of what I am trying to achieve: https://codepen.io/Rudchyk/pen/qNOEGj <div id="progressBar"> <div class=& ...

Issue arises when isomorphic-dompurify is used alongside dompurify in Next.js 13 causing compatibility problems

I am currently facing a compatibility problem involving isomorphic-dompurify and dompurify in my Next.js 13 project. It appears that both libraries are incompatible due to their dependencies on canvas, and I am struggling to find a suitable alternative. M ...

Problem uploading files with ajax in Laravel version 6

I am encountering an issue while attempting to save a PDF file along with other input values using Ajax in Laravel 6 without utilizing the form HTML element. The error message "Call to a member function getClientOriginalExtension() on null" keeps popping u ...

Navigating back to a specific segment of a dataset while using virtual scrolling

Virtual scrolling is a fantastic way to optimize rendering for large data sets. For this particular scenario, I am making use of the Angular Material CDK APIs to implement this feature. However, a specific requirement needs to be addressed - when a user ...

the redirection fails to initiate following the button press

I've encountered an issue similar to one discussed on stackoverflow, but I haven't been able to resolve it. I'm currently on the locking page and when a user clicks on a button, they should be redirected to the select-portfolio page. Howev ...

Leveraging Vue 2.0 and webpack to integrate components from an npm package

As I venture into setting up a project with webpack and Vue 2.0, I encountered a slight hiccup when trying to incorporate components from npm packages (such as vue-parallax) into my project. Upon installing the package, everything seems to be in place, bu ...

Angular 6 Error: 'bootbox' is Not Recognized

I have integrated bootbox into my Angular application following the guidance provided in this answer. However, upon building the project, I encountered the following error: error TS2304: Cannot find name 'bootbox'. Below is an excerpt from my ...

Using Buttons to Filter Data in React

My goal is to implement button functionality that filters data from a JSON file. Upon clicking a button, the state should be updated with the filtered JSON data and display the list with the updated information. Currently, I have four buttons for filteri ...

The 'myCtrl' parameter is invalid as it is not recognized as a function and is currently set to undefined

I'm having trouble resolving this issue. I've implemented other controllers in the same manner that are working fine, but this specific one is throwing an error Error: ng:areq Bad Argument" "Argument 'myCtrl' is not a function, got un ...