第一视图数据随角度中的第二个API调用而变化

时间:2019-01-17 11:23:34

标签: angular rxjs kendo-grid

我在一个组件中有两个视图。 在左侧(视图)和右侧(视图2)。 当我为view2调用第二个API时,ngOnInit上的API已经调用了左视图,如果还要更改view1中的数据。

https://stackblitz.com/edit/angular-kendo-2grid

在编辑服务文件上:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

import { tap } from 'rxjs/operators/tap';
import { map } from 'rxjs/operators/map';

const CREATE_ACTION = 'create';
const UPDATE_ACTION = 'update';
const REMOVE_ACTION = 'destroy';

@Injectable()
export class EditService extends BehaviorSubject<any[]> {
  constructor(private http: HttpClient) {
    super([]);
  }

  private data: any[] = [];

  public tempId = '';
  public read() {
    if (this.data.length) {
      return super.next(this.data);
    }


    this.fetch()
      .pipe(
        tap(data => {
          this.data = data;
        })
      )
      .subscribe(data => {
        super.next(data);
      });
  }

  public read2(id) {
    this.tempId = id;
    if (this.data.length) {
      return super.next(this.data);
    }


    this.fetch2()
      .pipe(
        tap(data => {
          this.data = data;
        })
      )
      .subscribe(data => {
        super.next(data);
      });
  }

  public save(data: any, isNew?: boolean) {
    const action = isNew ? CREATE_ACTION : UPDATE_ACTION;

    this.reset();

    this.fetch(action, data)
      .subscribe(() => this.read(), () => this.read());
  }

  public remove(data: any) {
    this.reset();

    this.fetch(REMOVE_ACTION, data)
      .subscribe(() => this.read(), () => this.read());
  }

  public resetItem(dataItem: any) {
    if (!dataItem) { return; }

    // find orignal data item
    const originalDataItem = this.data.find(item => item.ProductID ===     dataItem.ProductID);

    // revert changes
    Object.assign(originalDataItem, dataItem);

    super.next(this.data);
  }

  private reset() {
    this.data = [];
  }

  private fetch(action: string = '', data?: any): Observable<any[]> {
    return this.http
      .get(`https://jsonplaceholder.typicode.com/posts`)
      .pipe(map(res => <any[]>res));
  }

  private fetch2(action: string = '', data?: any): Observable<any[]> {
    return this.http
      .get(`https://jsonplaceholder.typicode.com/posts/${this.tempId}`)
      .pipe(map(res => <any[]>res));
  }

  private serializeModels(data?: any): string {
    return data ? `&models=${JSON.stringify([data])}` : '';
  }
}

在组件文件上:

从'rxjs / Observable'导入{Observable};     从'@ angular / core'导入{Component,OnInit,Inject};

import { GridDataResult } from '@progress/kendo-angular-grid';
import { State, process } from '@progress/kendo-data-query';

import { Product } from './model';
import { EditService } from './edit.service';

import { map } from 'rxjs/operators/map';

@Component({
  selector: 'my-app',
  template: `
   <div class="container-fluid">
    <div class="row">
      <div class="col-md-6">
      <kendo-grid
          [data]="view | async"
          [height]="533"
          [pageSize]="gridState.take" [skip]="gridState.skip"     [sort]="gridState.sort"
          [pageable]="true" [sortable]="true"
          (dataStateChange)="onStateChange($event)"
          (edit)="editHandler($event)" (remove)="removeHandler    ($event)"
          (add)="addHandler($event)"
        >
        <ng-template kendoGridToolbarTemplate>
            <button kendoGridAddCommand>Add new</button>
        </ng-template>

        <kendo-grid-column field="title" title="Product     Name"></kendo-grid-column>

        <kendo-grid-command-column title="command" width="220">
            <ng-template kendoGridCellTemplate let-dataItem>
                <button kendoGridEditCommand [primary]    ="true">Edit</button>
                <button kendoGridRemoveCommand>Delete</button>
                             <button (click)="clickIndividual    (dataItem.id)">Next Grid</button>
            </ng-template>
        </kendo-grid-command-column>
      </kendo-grid>

      <kendo-grid-edit-form [model]="editDataItem" [isNew]    ="isNew"
          (save)="saveHandler($event)"
          (cancel)="cancelHandler()">
      </kendo-grid-edit-form>
      </div>


      <div class="col-md-6">

            <kendo-grid
          [data]="view2 | async"
          [height]="533"
          [pageSize]="gridState.take" [skip]="gridState.skip"     [sort]="gridState.sort"
          [pageable]="true" [sortable]="true"
          (dataStateChange)="onStateChange($event)"
          (edit)="editHandler($event)" (remove)="removeHandler    ($event)"
          (add)="addHandler($event)"
        >
        <ng-template kendoGridToolbarTemplate>
            <button kendoGridAddCommand>Add new</button>
        </ng-template>

        <kendo-grid-column field="title" title="Product     Name"></kendo-grid-column>

        <kendo-grid-command-column title="command" width="220">
            <ng-template kendoGridCellTemplate>
                <button kendoGridEditCommand [primary]    ="true">Edit</button>
                <button kendoGridRemoveCommand>Delete</button>

            </ng-template>
        </kendo-grid-command-column>
      </kendo-grid>

      <kendo-grid-edit-form [model]="editDataItem" [isNew]    ="isNew"
          (save)="saveHandler($event)"
          (cancel)="cancelHandler()">
      </kendo-grid-edit-form>
      </div>

  </div>
</div>
  `
})
export class AppComponent implements OnInit {
  public view: Observable<GridDataResult>;
  public view2: Observable<GridDataResult>;
  public gridState: State = {
    sort: [],
    skip: 0,
    take: 10
  };

  public editDataItem: Product;
  public isNew: boolean;
  private editService: EditService;

  constructor(@Inject(EditService) editServiceFactory: any) {
    this.editService = editServiceFactory();
  }

  public ngOnInit(): void {
    this.view = this.editService.pipe(map(data => process(data,     this.gridState)));

    this.editService.read();
  }

  public clickIndividual(id) {
    this.view2 = this.editService.pipe(map(data => process(data,     this.gridState)));

    this.editService.read2(id);
  }

  public onStateChange(state: State) {
    this.gridState = state;

    this.editService.read();
  }

  public addHandler() {
    this.editDataItem = new Product();
    this.isNew = true;
  }

  public editHandler({ dataItem }) {
    this.editDataItem = dataItem;
    this.isNew = false;
  }

  public cancelHandler() {
    this.editDataItem = undefined;
  }

  public saveHandler(product: Product) {
    this.editService.save(product, this.isNew);

    this.editDataItem = undefined;
  }

  public removeHandler({ dataItem }) {
    this.editService.remove(dataItem);
  }
}

0 个答案:

没有答案