在我的情况下,如何正确发出PUT请求?

时间:2019-06-15 11:33:13

标签: angular typescript angular-reactive-forms

我是Angular的初学者。 当我单击“更新”按钮时,我只想将一个数组对象发送到后端。也许我做错了,因为我的方法没有发送表单更改。有人可以检查我的代码吗?在这种情况下如何正确进行PUT?

categories.component.ts

import {Component, OnInit} from '@angular/core';
import {FormArray, FormBuilder, FormGroup} from '@angular/forms';
import {Category} from '../../../shared/models/category';
import {Router} from '@angular/router';
import {ProductsService} from '../../../shared/services/products.service';

@Component({
  selector: 'app-category',
  templateUrl: './categories.component.html',
  styleUrls: ['./categories.component.scss']
})
export class CategoriesComponent implements OnInit {

  // categories = [
  //   {id: 1, name: 'veloglasses', uaName: 'Велоокуляри'},
  //   {id: 2, name: 'skiglasses', uaName: 'Лижні окуляри'},
  //   {id: 3, name: 'frames', uaName: 'Оправи'},
  //   {id: 4, name: 'accesories', uaName: 'Аксесуари'}
  // ];
  categories: Category[];

  categoryForm: FormGroup;

  isEditable = true;

  constructor(private fb: FormBuilder,
              private router: Router,
              private productService: ProductsService) {}

  ngOnInit() {
    const categoryArray = this.fb.array([]);
    this.categoryForm = this.fb.group({
      categories: categoryArray
    });

    this.productService.getCategories().subscribe(data => {
      this.categories = data;
      this.categories.forEach(category => {
        categoryArray.push(this.createCategoryGroup(category));
        console.log(category);
      });
    });
  }

  createCategoryGroup(category: any = {}) {
    return this.fb.group({
      id: this.fb.control(category.id),
      name: this.fb.control(category.name),
      uaName: this.fb.control(category.uaName)
    });
  }

  addCategory() {
    this.categoriesArray.push(this.createCategoryGroup());
  }

  onSubmit(i) {
    const category: Category = {
      id: this.categoriesArray.at(i).value.id,
      name: this.categoriesArray.at(i).value.name,
      uaName: this.categoriesArray.at(i).value.uaName
    };
    this.productService.updateCategory(category).subscribe(value => console.log(value));
    console.log(category);
    console.log(this.categoriesArray.at(i).value.name);
  }

  removeCategory(index) {
    this.categoriesArray.removeAt(index);
  }

  get categoriesArray() {
    return (this.categoryForm.get('categories') as FormArray);
  }

}

categories.component.html

<form id="productCategories" [formGroup]="categoryForm">
  <div class="form-group" formArrayName="categories">
    <div *ngFor="let category of categoriesArray.controls; let i = index;">
      <div class="row"  [formGroupName]="i">
        <input class="form-control" type="number" formControlName="id">
        <input class="form-control" type="text" formControlName="name">
        <input class="form-control" type="text" formControlName="uaName">
        <button class="btn btn-primary" type="button" (click)="removeCategory(i)">Remove</button>
        <button class="btn" type="submit" (click)="onSubmit(i)">Update</button>
      </div>
    </div>
    <button class="btn" type="button" (click)="addCategory()">Add Category</button>
  </div>
</form>

products.service.ts

import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Product} from '../models/product';
import {Category} from '../models/category';

const header = new HttpHeaders({'Content-Type': 'application/json'});

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

  constructor(private http: HttpClient) { }

  private categoriesUrl = 'http://localhost:8080/products/categories';

  ...

  public getCategories() {
    return this.http.get<Category[]>(this.categoriesUrl);
  }

  public getCategory(category) {
    return this.http.get<Category>(this.categoriesUrl + '/' + category.id);
  }

  public createCategory(category: Category) {
    return this.http.post<Category>(this.categoriesUrl + '/add', category);
  }

  public updateCategory(category: Category) {
    return this.http.put<Category>(this.categoriesUrl + '/' + category.id + '/update', category);
  }

  public deleteCategory(category) {
    return this.http.delete(this.categoriesUrl + '/' + category.id);
  }



}

My result

1 个答案:

答案 0 :(得分:0)

1)您收到任何CORS错误吗?    如果是,请配置代理,链接here

 {
  "/products/categories/*": {
    "target": "http://localhost:8080",
    "secure": false,
    "logLevel": "debug",
    "changeOrigin": true
  }
}

请澄清一下,既然您获得200 OK,则表示:

a)HTTP状态代码200 OK,表示成功对更新现有资源进行PUT。 不需要回复正文

b)HTTP状态代码201,用于成功PUT新资源,在Location标头字段中返回新资源的最特定URI,并在响应主体中回显该资源的任何其他相关URI和元数据。

由于得到200 OK并且只是更新,因此您需要在服务器中签入响应是否已更新,无需操纵UI。