尝试从Service提取模拟数据时为空响应

费萨尔·莫尼丁

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

1. app-routing.module.ts

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

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

}]

2.作物

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

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

3. CropData.ts

这是我的对象数组,我想访问subCategory并在网页上显示名称例如:当水稻用户点击则其应该得到的结果类似“香米”,“Ammamore” 当小麦用户点击那么它应该得到这样的结果“硬粒小麦”,“二粒小麦” 当用户点击大麦那么它的应该得到类似“ 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. 农作物公司
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>

这是我的高级代码,我不知道我要去哪里哪里,请帮助从对象数组中获取数据。[![在此处输入图片描述] [1]] [1]这是我的all-trades.component.html输出

  1. 当我单击Rice时,将其作为输出(URL获取change)

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

  1. 当我单击“小麦”时,我得到了

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

依此类推....我只想显示subCategory Array的名称。请给我解决方案。[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中分配模拟数据。已知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演示供您参考。您可以检查console的回应

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

响应改造时总是为空

来自分类Dev

AutoCloseable为空时的尝试资源

来自分类Dev

尝试将数据发布到服务器时,Braintree的payment_method_nonse为空

来自分类Dev

尝试将数据发布到服务器时,Braintree的payment_method_nonse为空

来自分类Dev

WooCommerce - 尝试更新数量时购物车项目数据为空

来自分类Dev

写入响应正文时,标题和响应正文为空

来自分类Dev

每次我尝试使用 Swift 和 Alamofire 将数据发布到 MySQL 数据库时,数据显示为空?

来自分类Dev

搜索成功后,当搜索文本框为空时,不会提取所有数据列表

来自分类Dev

正在从Firebase提取数据,但当应用程序呈现一次时authData为空

来自分类Dev

搜索成功后,当搜索文本框为空时,不会提取所有数据列表

来自分类Dev

尝试将数据插入空数据框中时出错

来自分类Dev

使用fetch()发布数据时为空

来自分类Dev

发布数据时对象为空

来自分类Dev

拍照时返回的数据为空

来自分类Dev

尝试通过php从json响应url获取数据时出错

来自分类Dev

尝试通过php从json响应url获取数据时出错

来自分类Dev

使用请求时响应中的主体为空

来自分类Dev

Nest SDM API:列出设备时为空响应

来自分类Dev

使用curl_multi_await时为空响应

来自分类Dev

RestTemplate - 当响应主体为空时处理潜在的 NullPointerException

来自分类Dev

尝试从MySql提取数据时出现语法错误

来自分类Dev

尝试使用Selenium WebDriver提取数据时出现问题

来自分类Dev

尝试从Web表中提取数据时出现硒错误

来自分类Dev

尝试使用 PHP 从 HTML 中提取数据时出错

来自分类Dev

尝试安装双启动系统时为空磁盘

来自分类Dev

尝试使用Boost读取xml时为空指针

来自分类Dev

尝试访问POJO属性时为空指针

来自分类Dev

尝试投射listbox.selecteditem时是否为空引用?

来自分类Dev

尝试安装双启动系统时为空磁盘

Related 相关文章

  1. 1

    响应改造时总是为空

  2. 2

    AutoCloseable为空时的尝试资源

  3. 3

    尝试将数据发布到服务器时,Braintree的payment_method_nonse为空

  4. 4

    尝试将数据发布到服务器时,Braintree的payment_method_nonse为空

  5. 5

    WooCommerce - 尝试更新数量时购物车项目数据为空

  6. 6

    写入响应正文时,标题和响应正文为空

  7. 7

    每次我尝试使用 Swift 和 Alamofire 将数据发布到 MySQL 数据库时,数据显示为空?

  8. 8

    搜索成功后,当搜索文本框为空时,不会提取所有数据列表

  9. 9

    正在从Firebase提取数据,但当应用程序呈现一次时authData为空

  10. 10

    搜索成功后,当搜索文本框为空时,不会提取所有数据列表

  11. 11

    尝试将数据插入空数据框中时出错

  12. 12

    使用fetch()发布数据时为空

  13. 13

    发布数据时对象为空

  14. 14

    拍照时返回的数据为空

  15. 15

    尝试通过php从json响应url获取数据时出错

  16. 16

    尝试通过php从json响应url获取数据时出错

  17. 17

    使用请求时响应中的主体为空

  18. 18

    Nest SDM API:列出设备时为空响应

  19. 19

    使用curl_multi_await时为空响应

  20. 20

    RestTemplate - 当响应主体为空时处理潜在的 NullPointerException

  21. 21

    尝试从MySql提取数据时出现语法错误

  22. 22

    尝试使用Selenium WebDriver提取数据时出现问题

  23. 23

    尝试从Web表中提取数据时出现硒错误

  24. 24

    尝试使用 PHP 从 HTML 中提取数据时出错

  25. 25

    尝试安装双启动系统时为空磁盘

  26. 26

    尝试使用Boost读取xml时为空指针

  27. 27

    尝试访问POJO属性时为空指针

  28. 28

    尝试投射listbox.selecteditem时是否为空引用?

  29. 29

    尝试安装双启动系统时为空磁盘

热门标签

归档