首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用JSON服务器在Angular 9中将数据检索到字段中?

如何使用JSON服务器在Angular 9中将数据检索到字段中?
EN

Stack Overflow用户
提问于 2020-06-10 13:19:11
回答 1查看 196关注 0票数 0

我有一个crud应用程序,上面有一个表单和一个表,它们位于两个独立的组件中,我希望在用户单击他想要查看的所选记录的按钮时从我的表中检索数据。当我通过console.log单击视图按钮时,我已经可以获得数据,但是我很难将其显示到表单内的字段中。有人能帮帮我吗?谢谢!

下面是我的表格模板:

代码语言:javascript
复制
    <app-update></app-update>
    <h4>My Products</h4>
    <table>
        <thead>
            <tr>
                <th>#</th>
                <th>Product Name</th>
                <th>Description</th>
                <th>Price</th>
                <th>Quantity</th>                            
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let product of products">
                <td>{{product.id}}</td>
                <td>{{product.name}}</td>
                <td>{{product.description}}</td>
                <td>{{product.price}}</td>
                <td>{{product.quantity}}</td>
                <td>
                    <a [routerLink]="['crud/update/, product.id']">Update</a>
                    <button class=btn btn-danger (click)="viewProduct(product.id)">View</button>
                    <button class=btn btn-danger (click)="deleteProduct(product.id)">Delete</button>
                </td>
            </tr>
        </tbody>
    </table>
</div>

这是我的表单模板

代码语言:javascript
复制
<div class="container" mt-5>
<h2>{{ header }}</h2>
<form (ngSubmit)="onSubmit(f)" #f="ngForm">
        <div class="col-md-12 form-group">
            <label for="">Name</label>
          <input type="text" class="form-control" [ngModel]="product.id" name ="name">
        </div>
        <div class="col-md-12 form-group">
            <label for="">Description</label>
          <input type="text" class="form-control" [ngModel]="product.description" name ="description">
        </div>
        <div class="col-md-12 form-group">
            <label for="">Price</label>
          <input type="text" class="form-control" [ngModel]="product.price" name ="price">
        </div>
        <div class="col-md-12 form-group">
            <label for="">Quantity</label>
          <input type="text" class="form-control" [ngModel]="product.quantity" name ="quantity">
        </div>
        <div class="col-md-12 form-group">
            <button class="btn btn-success btn-lg btn-block" (click)="createProduct(crudService.currentProduct)">
            Add
            </button>
            <button class="btn btn-success btn-lg btn-block" (click)="createProduct(crudService.currentProduct)">
             Update
            </button>
           <!-- <button type="submit" class="btn btn-primary">Add</button> -->
        </div>
</form>
</div>

这是我在console.log上的打字稿:

代码语言:javascript
复制
 viewProduct(id: number) {
    this.crudService.getById(id).subscribe(
      (data) => {
        this.crudService.getAll();
        console.log('User viewed successfully !', data);
      });
  }

下面是我的服务代码:

代码语言:javascript
复制
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from "@angular/common/http";
import { Observable } from 'rxjs';
import { throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

import { Product } from './product';

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

  private apiServer = "http://localhost:3000";
  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    })
  }

  }

  constructor(private httpClient: HttpClient) { }

  create(product): Observable<Product> {
    return this.httpClient.post<Product>(this.apiServer + '/products/', JSON.stringify(product), this.httpOptions)
    .pipe(
      catchError(this.errorHandler)
    )
  }  
  getById(id): Observable<Product> {
    return this.httpClient.get<Product>(this.apiServer + '/products/' + id)
    .pipe(
      catchError(this.errorHandler)
    )
  }

  getAll(): Observable<Product[]> {
    return this.httpClient.get<Product[]>(this.apiServer + '/products/')
    .pipe(
      catchError(this.errorHandler)
    )
  }
EN

回答 1

Stack Overflow用户

发布于 2020-06-10 13:56:47

希望您的viewProduct方法与表所在的组件相同。尝试将所选产品的服务数据分配给组件中的产品对象。

仅当数据对象的属性与产品对象相匹配或尝试手动设置产品对象的每个产品属性时,才使用展开运算符{...data}

代码语言:javascript
复制
viewProduct(id: number) {
    this.crudService.getById(id).subscribe(
      (data) => {
        this.crudService.getAll();
        // Use Spread operator only if you have properties of data objects matching with your product objects
        this.product = {...data};
        // Or else try to manually set each product property of product object like this
       // this.product.id = data.id;
        console.log('User viewed successfully !', data);
      });
 }

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62296374

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档