0

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

1.app-routing.module.ts

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

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

}]

2.作物.ts

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

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

3.作物数据.ts

这是我的对象数组,我想访问子类别并在网页上显示名称。例如:当用户点击大米时,它应该得到类似'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.1 crop.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 all-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 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. 作物组件.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] 这是我的 all-trades.component.html 输出

  1. 当我单击 Rice 时,我将其作为输出(Url get change )

[![在此处输入图像描述][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 回答 1

1

在您的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 中分配您的模拟数据。已知 BehaviorSubject 会发出初始数据

...

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响应

于 2020-11-16T01:13:56.980 回答