如何在Angular 8中正确使用setValue

问题描述 投票:0回答:2

我正在使用Angular反应形式。我想使用setvalue()使用API​​中的值初始化表单,然后执行更新。我当前正在执行get请求以获取产品,然后将产品值设置为从服务中获取的数据我可以通过将i传递给我的函数,然后将其传递给我的服务以通过ID获得产品。我正在从本地主机获取所有数据,所以没有堆栈闪电,因为我看不到它将如何帮助。创建伪数据将花费太长时间。如果您需要了解任何内容,请在评论中让我知道。

我的update-product.ts中的功能:

selectedId(id){
this.id = id +1 ;

this.homeService.getProduct(this.id).subscribe(data => {
 this.product = data;
}); 
this.updateProduct.setValue({
 id: this.product.id,
 productName: this.product.productName,
 category: this.product.category.categoryName,
 fullPrice: this.product.fullPrice,
 salePrice: this.product.salePrice,
 availability: this.product.availability,
 supplier: this.product.supplier.supplierName,
 discount: this.product.discount
});

}

我的表单具有三元运算符,可以在编辑模式下跟踪想要的产品。但我注意到有一个延迟。在显示数据之前,我必须单击两次按钮。如果单击其他产品上的编辑模式,则会显示我选择的先前产品的产品信息。我相信这是我所在的位置,但我不确定。这是正在发生的情况的快照。

我必须单击编辑按钮3次才能正确显示数据。enter image description here

当我单击第二个产品时,将显示第一个产品的数据,我必须总共单击3次才能从当前产品中获取数据。enter image description here

这是我的html文件:


  <!-- Table -->
  <form  [formGroup]="updateProduct" (ngSubmit)="onSubmit()">
      <p>
          Form Status: {{updateProduct.value|json}}
        </p>
  <div class="table-responsive">

    <table  class="table table-bordered table-striped">
      <thead>
      <tr>
        <th>Id</th>
        <th>Product</th>
        <th>Category</th>
        <th>FullPrice <i id ="asc-desc1"class="fas fa-angle-down" (click)="SortPrice($event)"></i></th>
        <th>Saleprice <i id ="asc-desc2"class="fas fa-angle-down" (click)="SortSale($event)"></i> </th>
        <th>Availablity</th>
        <th>Supplier</th>
        <th>Discount<i id ="asc-desc3"class="fas fa-angle-down" (click)="SortDiscount($event)"></i></th>
        <th>Edit</th>
      </tr>
      </thead>
      <tbody>

        <tr  *ngFor="let home of home | paginate:{itemsPerPage:20,currentPage: p} ; index as i">
        <ng-container *ngIf="editMode !== i">
        <td>{{home.id}}</td>
        <td>{{home.productName}}</td>
        <td>{{home.category.categoryName}}</td>
        <td>{{home.fullPrice}}</td>
        <td>{{home.salePrice}}</td>
        <td>{{home.availability}}</td>
        <td>{{home.supplier.supplierName}}</td>
        <td>{{home.discount }}</td>
      </ng-container>
      <ng-container *ngIf="editMode === i">

          <td><input class="form-control"  formControlName="id"  disabled></td>
          <td><input class="form-control" id="productName"  formControlName="productName" ></td>
          <td>
              <select class="form-control" formControlName="category">
                <option selected="selcected"  id="opt1" ></option>
                <option *ngFor="let category of categories" [value]= "category.categoryName">{{category.categoryName}}</option>
              </select>
            </td>
          <td><input class="form-control" id="fullprice" formControlName="fullPrice"></td>
          <td><input class="form-control" id="saleprice"   formControlName="salePrice"></td>
          <td><input type="checkbox" class="form-control" id="availability"  formControlName="availability" ></td>
          <td>
            <select class="form-control" formControlName="supplier" >
              <option *ngFor="let supplier of suppliers" [value]="supplier.supplierName">{{supplier.supplierName}}</option>
            </select>
          </td>
          <td><input class="form-control" formControlName="discount" id="discount" ></td>

        </ng-container>


      <!-- if assigned index to editMode matches -->

        <td class="text-right" id="tableDataBtns">
          <div class="btn-group" role="group">
            <button (click)="editMode === i ? editMode = null : editMode = i" data-toggle="modal" data-target="#updateProduct" type="button" class="btn btn-secondary">
              <ng-container *ngIf="editMode === i"><i class="far fa-save"></i></ng-container>
              <ng-container *ngIf="editMode !== i"><i (click)="selectedId(i)" class="far fa-edit"></i></ng-container>
            </button>
            <button (click)="selectedId(i)" type="button" data-toggle="modal" data-target="#deleteProduct" class="btn btn-danger"><i class="far fa-trash-alt"></i></button>
          </div>
        </td>
      </tr>
      </tbody>
    </table>

    <pagination-controls class="myPagination" (pageChange)="p= $event"></pagination-controls>
  </div>
  </form>

这是我的ts文件:

import { Component, OnInit } from '@angular/core';
import { Product } from '../model/Product';
import { Category } from '../model/Availability';
import { Supplier } from '../model/Supplier';
import { Home } from '../model/Home';
import { HomeService } from '../service/Home.service';
import { SupplierService } from '../service/Supplier.service';
import { CategoryService } from '../service/Category.service';
import { FormGroup, FormControl } from '@angular/forms'



@Component({
  selector: 'app-update-product',
  templateUrl: './update-product.component.html',
  styleUrls: ['./update-product.component.scss']
})





export class UpdateProductComponent implements OnInit {
  availability:boolean;
  category:number;
  orderBy: String;
  Ascdesc: String;
  page = 0;
  home: Home[];
  product: Product;
  categories: Category[];
  suppliers: Supplier[];
  selectedCategory: Category;
  id: number;
  public currentProduct: number;



selectedId(id){
this.id = id +1 ;

this.homeService.getProduct(this.id).subscribe(data => {
  this.product = data;
}); 
this.updateProduct.setValue({
  id: this.product.id,
  productName: this.product.productName,
  category: this.product.category.categoryName,
  fullPrice: this.product.fullPrice,
  salePrice: this.product.salePrice,
  availability: this.product.availability,
  supplier: this.product.supplier.supplierName,
  discount: this.product.discount
});
console.log(this.id);
}


  selectCategory (category) {
       this.category = category.category;
   }

   available(boolean){

    this.availability = boolean;
    }

    update($event){
      this.homeService.getByParm(this.availability,this.category).subscribe(data => {
        this.home = data;
      }); 

    }


    updateProduct = new FormGroup({
      id: new FormControl(''),
      productName: new FormControl(''),
      category: new FormControl(''),
      fullPrice: new FormControl(''),
      salePrice: new FormControl(''),
      availability: new FormControl(''),
      supplier: new FormControl(''),
      discount: new FormControl(''),

    });




constructor(private homeService: HomeService,private supplierService: SupplierService,private categoryService: CategoryService) { }


SortPrice($event:any){
  let icon = document.getElementById("asc-desc1");
  if(icon.className === "fas fa-angle-down"){
    icon.className ="fas fa-angle-up";
    this.homeService.getByPriceAsc().subscribe(data => {
    this.home = data;
  });
  }else{
    icon.className ="fas fa-angle-down"
    this.homeService.getByPriceDesc().subscribe(data => {
      this.home = data;
    });
  };

}


onSubmit() {
 // TODO: Use EventEmitter with form value
  console.warn(this.updateProduct.value);
}
SortSale($event:any){
  let icon = document.getElementById("asc-desc2");
  if(icon.className === "fas fa-angle-down"){
    icon.className ="fas fa-angle-up";
    this.homeService.getBySaleAsc().subscribe(data => {
    this.home = data;
  });
  }else{
    icon.className ="fas fa-angle-down"
    this.homeService.getBySaleDesc().subscribe(data => {
      this.home = data;
    });
  };

}
SortDiscount($event:any){
  let icon = document.getElementById("asc-desc3");
  if(icon.className === "fas fa-angle-down"){
    icon.className ="fas fa-angle-up";
    this.homeService.getByDiscountAsc().subscribe(data => {
    this.home = data;
  });
  }else{
    icon.className ="fas fa-angle-down"
    this.homeService.getByDiscountDesc().subscribe(data => {
      this.home = data;
    });
  };

}


ngOnInit() {


  this.supplierService.getAll().subscribe(data => {
    this.suppliers = data;
  });

    this.homeService.getAll().subscribe(data => {
    this.home = data;
  });




  this.categoryService.getAll().subscribe(data => {
    this.categories = data;
  });

}

}
javascript angular
2个回答
0
投票

如果您不想使用ngrx,更好的方法是为您的editMode创建behavioursubject

editStarted = new BehaviorSubject(false);editItemChanged = new BehaviorSubject({});

在您的服务类中创建此文件,并在需要时订阅它。因此,一旦您通过在组件上调用next()触发了editStarted或editItemChanged触发器,它便可以执行您想执行的代码。


0
投票

您的setValue()必须位于subscribe()的内部,否则它将始终在subscribe()完成之前运行。

selectedId(id){
    this.id = id + 1;

    this.homeService.getProduct(this.id).subscribe(data => {
        this.product = data;
        this.updateProduct.setValue({
            id: this.product.id,
            productName: this.product.productName,
            category: this.product.category.categoryName,
            fullPrice: this.product.fullPrice,
            salePrice: this.product.salePrice,
            availability: this.product.availability,
            supplier: this.product.supplier.supplierName,
            discount: this.product.discount
        });
    });

    console.log(this.id);
}

这可以解释为什么总是需要两次尝试。如果您不确定如何工作,请阅读以下内容:https://angular.io/guide/observables

© www.soinside.com 2019 - 2024. All rights reserved.