Javascript 尝试从服务获取模拟数据时响应为空

Javascript 尝试从服务获取模拟数据时响应为空,javascript,angular,typescript,routes,dynamic-routing,Javascript,Angular,Typescript,Routes,Dynamic Routing,我想从对象数组中获取和显示数据。 我已经创建了参数化路线 1。应用程序路由.module.ts const routes: Routes = [ { path: 'all-trades', component: AllTradesComponent, }, { path: 'crop/:name', component: CropComponent }] export class Crop { name: string; check

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

1。应用程序路由.module.ts

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

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

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

export class Subcategory {
    id: number;
    name: string;
    isActive: boolean;
}
2。Crop.ts

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

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

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

export class Subcategory {
    id: number;
    name: string;
    isActive: boolean;
}
3。CropData.ts

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

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

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

export class Subcategory {
    id: number;
    name: string;
    isActive: boolean;
}
这是我的对象数组,我想访问子类别并在网页上显示名称。 例如:当用户单击Rice时,它应该会得到类似“Basmati”、“Ammamore”这样的结果 当用户点击小麦时,它应该会得到像“硬粒”、“埃默”这样的结果 当用户点击大麦时,其结果应该是“无壳大麦”、“大麦片”

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裁剪服务.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];


  }
}
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)); 
}
}
4.2裁剪服务.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];


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

7。裁剪组件.html

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

{{category.id}
这是我的eniter代码,我不知道哪里出了问题,请帮助从对象数组中获取数据。 [![在此处输入图像描述][1][1] 这是我的all-trades.component.html输出

  • 当我单击Rice时,我将其作为输出(Url get change)
  • [![在此处输入图像描述][2][2]

  • 当我点击小麦,我得到这个
  • [![在此处输入图像描述][3][3]

    等等。。。。 我只想显示子类别数组的名称。 请给我答案。 [1]: [2]:
    [3] :

    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上,如果最终使用此方法,则忘记在行为主体中分配模拟数据。已知行为子对象发出初始数据

    ...
    
    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)); 
        }
    
    }
    
    。。。
    从“../shared/cropdata”导入{CROP};
    出口级农产品服务{
    private selectedCrop=new BehaviorSubject(CROP);//传递裁剪模拟数据
    设置作物(作物:作物[]){
    this.selectedCrop.next(裁剪);
    }
    getCrop(){
    this.selectedCrop.asObservable().pipe(skipWhile(val=>val==null));
    }
    }
    

    已创建一个供您参考。您可以在编辑其给我错误(属性)CropService后检查
    控制台
    的响应

    。CropData:Crop类型“Crop[]”缺少类型“Crop”中的以下属性:name、checked、Subcategorits(2739)您能为我提供有关stackblitz的类似示例吗,我想访问子类别数组下的名称。。。。我现在很困惑。。。不明白。。。如果没有,请修改我的代码。。。。你真是太好了。。。please@faisalmoinuddin我已经更新了上面的答案。由于模拟数据接口是基于CropData.ts的Crop[],因此还需要将服务中包含它们的变量分配给类型为Crop[]的变量。我可以知道这是否对你方有效吗?我已经创建了一个Stackblitz演示供你参考。我已经更新了上面的答案。您可以在附带的stackblitz上查看控制台。希望有帮助:)是的,完成了!再次感谢