Angular ReplaySubject获取重复或过时的值

时间:2018-03-15 02:28:12

标签: angular observable

我的观察能力存在问题,我有一个下拉列表,其值来自后端 我有其他组件可以添加或删除应该反映在该下拉列表中的值。 每当我添加一个值而不是下拉列表时,我会看到双值,更糟糕的是当我删除一个值时,它仍然在下拉列表中

正如标题建议我使用ReplaySubject如下

SERVICE

  editDeleteCategoryEvent: EventEmitter<any> = new EventEmitter<any>();
  editDelteManufacturerEvent: EventEmitter<any> = new EventEmitter<any>();

  categories$: Subject<any[]> = new ReplaySubject<any[]>(1);

  constructor(private http: HttpClient, private global: GlobalUrlService) {
    this.getCategories();
  }

  getCategories() {
    this.http.get<any[]>(this.global.getProductCategoryUrl())
      .subscribe(
      categories => this.categories$.next(categories),
      error => this.categories$.error(error)
      );
  }

  subscribeToCategories(): Observable<any[]> {
    return this.categories$;
  }

我启动下拉列表的组件

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';

import { ProductConfigService } from '../../../../services/product-config.service';
import { Message } from 'primeng/primeng';

@Component({
  selector: 'app-add-product',
  templateUrl: './add-product.component.html',
  styleUrls: ['./add-product.component.css']
})
export class AddProductComponent implements OnInit {

    constructor(private formBuilder: FormBuilder, private productService: ProductConfigService) {
        productService.addProductEvent.subscribe(() => this.display = true);
        productService.editDeleteCategoryEvent.subscribe(() => this.getCategories());
      }

      ngOnInit() {
        this.getCategories();
      }

      clearForm() {
        this.form.reset();
      }

      getCategories() {

        this.productCategories = [];
        this.productCategories.push({ label: 'Product Category', value: null });
        this.productService.subscribeToCategories().subscribe(categories => {
          categories.map(category => {
    // since the subscriber gives me double values, i added the hack but on delete its not working, and moreover it should bring double values
                if (!this.productCategories.find(x =>  x.label === category.categoryName)) {
                  this.productCategories.push({ label: category.categoryName, value: category.categoryName });
                }
              });
            });
          }

我添加或删除类别的组件:

import { Component, OnInit } from '@angular/core';
import { ProductConfigService } from '../../../services/product-config.service';
import { ConfirmationService, Message } from 'primeng/primeng';

@Component({
  selector: 'app-product-setting',
  templateUrl: './product-setting.component.html',
  providers: [ConfirmationService],
  styleUrls: ['./product-setting.component.css']
})
export class ProductSettingComponent implements OnInit {

  productTypes = [];

  products = [];

  msgs: Message[] = [];

  // holds the product categories
  categories = [];

  constructor(private productService: ProductConfigService,
    private confirmationService: ConfirmationService) { }
    addCategory(category) {
        this.msgs = [];
        this.productService.addCategory({ categoryName: category }).subscribe(
          sucess => {
            this.categories = [];
            this.msgs.push({ severity: 'success', summary: 'Success', detail: 'Added the category: ' + category });
    // bring the newly categories list from the back end with the thought that subscribers should be refreshed
            this.productService.getCategories();
    // notify the previous component to resubsribe
            this.productService.editDeleteCategoryEvent.emit();
          },
          error => this.msgs.push({ severity: 'error', summary: 'Error Adding category', detail: error.error }));
      }

1 个答案:

答案 0 :(得分:0)

这是一个live工作示例。看看HttpFake服务(这只是一个如何管理服务器上的东西的例子)。

您初始化下拉列表的组件(我认为删除类别更合适)

getCategories() {
    this.productService.subscribeToCategories().subscribe(categories => {
        if (Array.isArray(categories)) {
            this.productCategories = categories.map(category => ({
              label: category.categoryName, value: category.categoryName }));
        } else {
            this.productCategories.push({ label: categories.categoryName, value: categories.categoryName });
        }
        console.log(this.productCategories);
    }, err => console.log(err), () => console.log('I completed too'));
}


remove(category) {
    category = { categoryName: category.label };
    this.productService.removeCategory(category)
        .subscribe(console.log); 
}

您添加类别的组件:

addCategory(product: any) {
    const category = product.categoryName;
    this.msgs = [];
    this.productService.addCategory({ categoryName: category })
        .subscribe(sucess => {
            this.categories = [];

            this.msgs.push({ severity: 'success', summary: 'Success', detail: 'Added the category: ' + category });;
          },
        error => this.msgs.push({ severity: 'error', summary: 'Error Adding category', detail: error.error }));
}

您的服务

addCategory(category: any): Observable<any> { 
  return this.http.post(`htps://url/categories`, category)
     .pipe(
         tap(data => this.categories.next(data))
     );
}

removeCategory(category: any) {
   return this.http.delete(`htps://url/categories`, category)
      .pipe(
          tap(data => this.getCategories())
      );
}