如何使用ng-crud-table在Angular7中使用诺言插入数据

时间:2019-04-22 11:04:04

标签: web promise asp.net-web-api2 observable angular7

我尝试在演示项目之后使用ng-crud-table进行Crud操作,但停留在POST,DELETE和PUT上,要求如何将其与示例代码中提供的服务一起使用 我正在服务文件

中点击在Angular7中创建CRUD的链接。
 import {Injectable} from '@angular/core';
       import {HttpClient} from '@angular/common/http';
       import {DataSource, RequestMetadata, PagedResult} 
       from'../../lib/ngcrud- table';
       import {DataSort, DataFilter} from '../../lib/ng-data-table/base';
       import {arrayPaginate} from '../../lib/common/utils';

       @Injectable({
       providedIn: 'root'
       })
      export class DemoService implements DataSource {

     // url: string = 'assets/players.json';
        url:string = 'http://localhost:22387/api/Yarn/YarnColors';
    // url_create : string ='http://localhost:22387/api/Yarn/YarnColors';
    // primaryKeys: string[] = ['id'];
       primaryKeys: string[] = ['YarnColorID'];

      private dataFilter: DataFilter;
      private dataSort: DataSort;

     constructor(private http: HttpClient) {
     this.dataFilter = new DataFilter();
     this.dataSort = new DataSort();
    }

   getItems(requestMeta: RequestMetadata): Promise<PagedResult> {
   const page = requestMeta.pageMeta.currentPage;
   this.dataFilter.filters = requestMeta.filters;
   this.dataFilter.globalFilterValue = requestMeta.globalFilterValue;
   this.dataSort.sortMeta = requestMeta.sortMeta;
   const perPage = requestMeta.pageMeta.perPage;

    return this.http.get<PagedResult>(this.url)
   .toPromise()
   .then(function (res) {
    const rows: any[] = res || [];
    const filteredData = this.dataFilter.filterRows(rows);
    const sortedData = this.dataSort.sortRows(filteredData);
    const pageData = arrayPaginate(sortedData, page, perPage);
    const totalCount = sortedData.length;
    const pageCount = pageData.length;
    const result = <PagedResult>{
      'items': pageData,
      '_meta': {
        'totalCount': totalCount,
        'pageCount': pageCount,
        'currentPage': page,
        'perPage': perPage
      }
     };
    return result;
    }.bind(this))
    .catch(this.handleError);
   }

  getItem(row: any): Promise<any> {
  const filters = {};
  for (const key of this.primaryKeys) {
  filters[key] = {value: row[key]};
 }
 const requestMeta = <RequestMetadata> {
  pageMeta: {currentPage: 1},
  filters: filters,
 };
 return this.getItems(requestMeta)
  .then(data => data.items[0]);
 }

         post(item: any): Promise<any> {
        //this.url_create='http://localhost:22387/api/Yarn/CreateYarn';
        // this.data.items.push(item); // exist in component
        return new Promise((resolve) => {
          setTimeout(() => resolve(item), 250);
        });
         }

          put(item: any): Promise<any> {
        // this.data.items[this.findSelectedItemIndex(item)] = item; // exist in 
           component
        return new Promise((resolve) => {
          setTimeout(() => resolve(item), 250);
        });
        }

        delete(item: any): Promise<any> {
        // this.data.items.splice(this.findSelectedItemIndex(item), 1); // exist 
        in component
        return new Promise((resolve) => {
          setTimeout(() => resolve(item), 250);
        });
        }

        getOptions(url: string, parentId: any): Promise<any> {
        return this.http.get(url)
          .toPromise()
          .then((response: any) => {
            const result = response.filter((value: any) => {
              return value['parentId'] === parentId;
            });
            return new Promise((resolve) => {
              setTimeout(() => resolve(result), 1000);
            });
          })
          .catch(this.handleError);
        }

         private handleError(error: any) {
        let errorMessage = '';
        if (error.error instanceof ErrorEvent) {
          // client-side error
          errorMessage = `Error: ${error.error.message}`;
        } else {
          // server-side error
          errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
        }
        return Promise.reject(errorMessage);
        }

         }
     create the Table component
    ```Table.ts file
        import { Component, OnInit } from '@angular/core';
        import {HttpClient} from '@angular/common/http';
        import {Column, Settings} from '../../lib/ng-data-table';
        import {CdtSettings, DataTable, DataManager} from '../../lib/ng-crud- 
        table';
        import {DemoService} from '../demo/demo.service';
        import {getColumnsPlayers} from '../demo/columns';
        import {Yarncolorname} from '../yarncolorname';

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

      table: DataTable;
      columns: Column[];
      dataManager: DataManager;

      settings: Settings = <Settings>{
        virtualScroll: true,
        rowHeightProp: '$$height',
       };

       serverSideSettings: CdtSettings = <CdtSettings>{
        virtualScroll: true,
        crud:true,
       };

        constructor(private service: DemoService, private http: HttpClient) {
        this.columns = getColumnsPlayers();
        for (const column of this.columns) {
          column.editable = false;
        }
        this.table = new DataTable(this.columns, this.settings);
        this.dataManager = new DataManager(this.columns, this.serverSideSettings, 
        this.service);
        }
        ngOnInit() {
        this.table.events.onLoading(true);
        // this.http.get<any[]>('assets/players.json').subscribe(data => {
          this.http.get<any[]> 
         ('http://localhost:22387/api/Yarn/YarnColors').subscribe(data => {
          for (const row of data) {
            row.$$height = (row.exp > 1000000) ? 40 : 25;
          }
          this.table.rows = data;
          console.log(data);
          this.table.events.onLoading(false);
         });

         }
        // post(item: any): Promise<any> {
        //   



      //this.http.post<Promise<any>='http://localhost:22387/api/Yarn/CreateYarn';
      //   // this.data.items.push(item); // exist in component
      //   return new Promise((resolve) => {
      //     setTimeout(() => resolve(item), 250);
      //   });
       }

    ```Fetch Data from database using get request with service.ts file
         this.table.events.onLoading(true);
        // this.http.get<any[]>('assets/players.json').subscribe(data => {
          this.http.get<any[]> 
         ('http://localhost:22387/api/Yarn/YarnColors').subscribe(data => {
          for (const row of data) {
            row.$$height = (row.exp > 1000000) ? 40 : 25;
          }
          this.table.rows = data;
          console.log(data);
          this.table.events.onLoading(false);
          });
    ```
    But i havent any idea how can i utilize this other function POST,PUT DELETE 
    ``` 
         post(item: any): Promise<any> {
         //this.url_create='http://localhost:22387/api/Yarn/CreateYarn';
         // this.data.items.push(item); // exist in component
         return new Promise((resolve) => {
          setTimeout(() => resolve(item), 250);
         });
         }

         put(item: any): Promise<any> {
        // this.data.items[this.findSelectedItemIndex(item)] = item; // exist in 
         component
         return new Promise((resolve) => {
          setTimeout(() => resolve(item), 250);
          });
          }

         delete(item: any): Promise<any> {
        // this.data.items.splice(this.findSelectedItemIndex(item), 1); // exist 
          in component
          return new Promise((resolve) => {
          setTimeout(() => resolve(item), 250);
        });
         }

如何使用我编写的服务来利用POST,DELETE和PUT功能?

0 个答案:

没有答案