尝试从服务中获取模拟数据时出现空响应

Empty response when trying to fetch mock data from Service

我想从对象数组中获取和显示数据。 我已经创建了参数化路由。

1.应用-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

这是我的对象数组,我想访问子类别并在网页上显示 名称。 例如:当用户点击 Rice 时,它​​应该得到类似 'Basmati'、'Ammamore' 的结果 当用户点击小麦时,它应该得到像 'Durum'、'Emmer' 这样的结果 当用户点击大麦时,它应该得到像 '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.1crop.service.ts // 首先我尝试了这个逻辑

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 // 然后我尝试了这个逻辑

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)); 
}
}

两种情况我都失败了。

5.1全-trades.components.ts

// 首先尝试使用函数

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) { }

// Here I tried to make use of function but still its doesnot giving me the desire result

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全行业-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. 裁剪-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>

这是我的 eniter 代码我不知道我哪里出错了请帮助从对象数组中获取数据。 [![在此处输入图片描述][1]][1] 这是我的全部交易。component.html输出

  1. 当我点击 Rice 时,我将其作为输出(Url 找零)

[![在此处输入图片描述][2]][2]

  1. 当我点击小麦时,我得到了这个

[![在此处输入图片描述][3]][3]

等等.... 我只想显示子类别数组的名称。 请给我解决方案。 [1]: https://i.stack.imgur.com/kxdyj.png [2]: https://i.stack.imgur.com/OOAtc.png [3]: https://i.stack.imgur.com/PVcfT.png

在您的 4.1 上,您似乎忘记将模拟数据分配给变量

....

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


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

  constructor() { }

  CropData: Crop[] = CROP;        // Assign the value


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

在您的 4.2 上,如果您最终使用此方法,您也忘记了在 BehaviorSubject 中分配模拟数据。已知 BehaviorSubjects 会发出初始数据

...

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


export class CropService {

private selectedCrop = new BehaviorSubject<Crop[]>(CROP);   // Pass CROP mock data

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

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

}

创建了一个Stackblitz Demo供大家参考。您可以检查 console 的响应