首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用angular2通过服务响应将数据设置为@Input声明变量

如何使用angular2通过服务响应将数据设置为@Input声明变量
EN

Stack Overflow用户
提问于 2017-02-14 15:40:37
回答 1查看 1.2K关注 0票数 0

我用的是“NG2-智能桌”。在“NG2-智能表.组件”中,我有

代码语言:javascript
复制
import {
  Component, Input, Output, SimpleChange, EventEmitter,
  OnChanges
} from '@angular/core';

import { Grid } from './lib/grid';
import { DataSource } from './lib/data-source/data-source';
import { Row } from './lib/data-set/row';

import { deepExtend } from './lib/helpers';
import { LocalDataSource } from './lib/data-source/local/local.data-source';

import { ViewListCustomersComponent} from '../app/view-list-customers/view-list-customers.component';
import any = jasmine.any;

@Component({
  selector: 'ng2-smart-table',
  styles: [require('./ng2-smart-table.scss')],
  template: require('./ng2-smart-table.html')
  //template: require('../app/view-list-customers/ng2-smart-table.html')
})

export class Ng2SmartTableComponent implements OnChanges {

  @Input() source: any;
  @Input() settings: Object = {};

  @Output() public rowSelect: EventEmitter<any> = new EventEmitter<any>();
  @Output() public userRowSelect: EventEmitter<any> = new EventEmitter<any>();
  @Output() public delete: EventEmitter<any> = new EventEmitter<any>();
  @Output() public edit: EventEmitter<any> = new EventEmitter<any>();
  @Output() public create: EventEmitter<any> = new EventEmitter<any>();

  @Output() public deleteConfirm: EventEmitter<any> = new EventEmitter<any>();
  @Output() public editConfirm: EventEmitter<any> = new EventEmitter<any>();
  @Output() public createConfirm: EventEmitter<any> = new EventEmitter<any>();

  @Input() defaultSettings:Object;

  @Input() customerDetailsItem : Object;
  data:Array<string>;
  protected grid: Grid;

  constructor(public viewListCustomersComponent:ViewListCustomersComponent) {
    console.log("==isEdit======== "+this.source);
  }

  ngOnChanges(changes: {[propertyName: string]: SimpleChange}): void {
    console.log("=================ngOnChanges=================");
    if (this.grid) {
      if (changes['settings']) {
        this.grid.setSettings(this.prepareSettings());
      }
      if (changes['source']) {
        this.grid.setSource(this.source);
      }
    } else {
      this.initGrid();
    }

  }

  onAdd(event): boolean {
    console.log("=================onAdd=================");
    event.stopPropagation();
    if (this.grid.getSetting('mode') === 'external') {
      this.create.emit({
        source: this.source
      });
    } else {
      this.grid.createFormShown = true;
    }
    return false;
  }

  onUserSelectRow(row: Row): void {
    console.log("=================onUserSelectRow=================");
    this.grid.selectRow(row);
    this.userRowSelect.emit({
      data: row.getData(),
      source: this.source
    });

    this.onSelectRow(row);
  }

  onSelectRow(row: Row): void {
    console.log("=================onSelectRow=================");
    this.grid.selectRow(row);
    this.rowSelect.emit({
      data: row.getData(),
      source: this.source
    });
  }

  onEdit(row: Row, event): boolean {
    console.log("=================onEdit=================");
    event.stopPropagation();
    this.onSelectRow(row);

    if (this.grid.getSetting('mode') === 'external') {
      this.edit.emit({
        data: row.getData(),
        source: this.source
      });
    } else {
      this.grid.edit(row);
    }
    return false;
  }

  onDelete(row: Row, event): boolean {
    console.log("=================onDelete=================");
    event.stopPropagation();

    if (this.grid.getSetting('mode') === 'external') {
      this.delete.emit({
        data: row.getData(),
        source: this.source
      });
    } else {
      this.grid.delete(row, this.deleteConfirm);
    }
    return false;
  }

  onCreate(row: Row, event): boolean {
    console.log("=================onCreate=================")
    event.stopPropagation();

    this.grid.create(row, this.createConfirm);
    return false;
  }

  onSave(row: Row, event): boolean {
    console.log("=================onSave================="+row.getCells()[0].getValue());

    event.stopPropagation();
    console.log("dddddddddddd "+this.viewListCustomersComponent.onCustomerEdit(row.getCells()));
    //this.grid.save(row, this.editConfirm);
    return false;
  }

  onActive(row: Row, event): boolean {
    console.log("=================onActive=================");
    event.stopPropagation();
    this.grid.save(row, this.editConfirm);
    return false;
  }
  protected initGrid(): void {
    this.source = this.prepareSource();
    this.grid = new Grid(this.source, this.prepareSettings());
    this.grid.onSelectRow().subscribe((row) => this.onSelectRow(row));
  }

  protected prepareSource(): DataSource {
    if (this.source instanceof DataSource) {
      return this.source;
    } else if (this.source instanceof Array) {
      return new LocalDataSource(this.source);
    }

    return new LocalDataSource();
  }

  protected prepareSettings(): Object {
    console.log("============this.settings======="+this.settings)
    return deepExtend({}, this.defaultSettings, this.settings);
  }
}

在我的app.compont.html里我写了

代码语言:javascript
复制
<ng2-smart-table  [settings]="settings" [source]="data" [defaultSettings]="defaultSettings" [customerDetailsItem]="customerDetailsItem"></ng2-smart-table>

在我的app.componebt.ts文件中

代码语言:javascript
复制
data : CustomerDetailsItem[];
constructor(public service:ViewListCustomerServiceService) 
{
  this.service.getCustomerItemList().subscribe(lst =>this.data=(lst));
}

但是在浏览器控制台中,我得到的是空表和消耗。

代码语言:javascript
复制
EXCEPTION: Error in ./appComponent class appComponent - inline template:70:100 caused by: 'undefined' is not a function (evaluating 'source.setPaging(1, this.getSetting('pager.perPage'), false)')

main.bundle.js:50314ORIGINAL异常:“未定义”不是一个函数(计算'source.setPaging(1,this.getSetting(‘pager.perPage’,false)') main.bundle.js:50321

如果我将静态值传递给" data“变量,那么我将得到带有默认数据的表。例如:

代码语言:javascript
复制
data=[
{

  id:1,

  "name":"Customer 1",

  "details":"Customer 1",

  "active":false

},

{

  "id":2,

  "name":"Customer 2",

  "details":"Customer 2 details goes here",

  "active":false

}];

我还检查了我的服务响应,和上面一样。

请建议我该怎么做。

这是我的app.Component.service.ts代码

代码语言:javascript
复制
@Injectable()
export class appComponentService {

  constructor(private http:Http) { }

  getCustomerItemList():Observable<CustomerDetailsItem[]> {

    let response = this.http.get(`${AppSettings.BACK_ENDPOINT}/nextrow/list-customers/?access_token=`+sessionStorage.getItem("access_token"));
    let customerDetailItems = response.map(mapCustomerItems);
    return customerDetailItems;
  }
}
function mapCustomerItems(response:Response):CustomerDetailsItem[] {
  let customerDetailsItem =response.json();
  return customerDetailsItem;
}

ng2-smart-table.html

代码语言:javascript
复制
<div class="ng2-smart-table-container">
代码语言:javascript
复制
<tr class="ng2-smart-titles" *ngIf="!grid.getSetting('hideHeader')">
  <th *ngIf="grid.showActionColumn('left')" class="ng2-smart-actions">
    <div class="ng2-smart-title">{{ grid.getSetting('actions.columnTitle') }}</div>
  </th>
  <th *ngFor="let column of grid.getColumns()" class="ng2-smart-th {{ column.id }}" [ngClass]="column.class">
    <div class="ng2-smart-title">
      <ng2-smart-table-title [source]="source" [column]="column"></ng2-smart-table-title>
    </div>
  </th>
  <th *ngIf="grid.showActionColumn('right')" class="ng2-smart-actions">
    <div class="ng2-smart-title">{{ grid.getSetting('actions.columnTitle') }}</div>
  </th>
</tr>
代码语言:javascript
复制
<tr *ngIf="grid.createFormShown">
  <td class="ng2-smart-actions">
    <a href="#" class="ng2-smart-action ng2-smart-action-add-create" [innerHTML]="grid.getSetting('add.createButtonContent')" (click)="onCreate(grid.getNewRow(), $event)"></a>
    <a href="#" class="ng2-smart-action ng2-smart-action-add-cancel" [innerHTML]="grid.getSetting('add.cancelButtonContent')" (click)="grid.createFormShown = false;"></a>
  </td>
  <td *ngFor="let cell of grid.getNewRow().getCells()">
    <ng2-smart-table-cell [cell]="cell" [inputClass]="grid.getSetting('add.inputClass')" (edited)="onCreate(grid.getNewRow(), $event)"></ng2-smart-table-cell>
  </td>
</tr>

</thead>

<tbody>

<tr *ngFor="let row of grid.getRows()" (click)="onUserSelectRow(row)" class="ng2-smart-row" [ngClass]="{selected: row.isSelected}">
  <td *ngIf="!row.isInEditing && grid.showActionColumn('left')" class="ng2-smart-actions">
    <a href="#" *ngIf="grid.getSetting('actions.edit')" class="ng2-smart-action ng2-smart-action-edit-edit" [innerHTML]="grid.getSetting('edit.editButtonContent')" (click)="onEdit(row, $event)"></a>
    <a href="#" *ngIf="grid.getSetting('actions.delete')" class="ng2-smart-action ng2-smart-action-delete-delete" [innerHTML]="grid.getSetting('delete.deleteButtonContent')" (click)="onDelete(row, $event)"></a>
  </td>
  <!--<td *ngIf="row.isInEditing" class="ng2-smart-actions">
    <a href="#" class="ng2-smart-action ng2-smart-action-edit-save" [innerHTML]="grid.getSetting('edit.saveButtonContent')" (click)="onSave(row, $event)"></a>
    <a href="#" class="ng2-smart-action ng2-smart-action-edit-cancel" [innerHTML]="grid.getSetting('edit.cancelButtonContent')" (click)="row.isInEditing = false;"></a>
  </td>-->
  <td *ngFor="let cell of row.getCells()">
    <ng2-smart-table-cell [cell]="cell" [mode]="grid.getSetting('mode')" [inputClass]="grid.getSetting('edit.inputClass')" (edited)="onSave(row, $event)"></ng2-smart-table-cell>
  </td>
  <td *ngIf="row.isInEditing" class="ng2-smart-actions">
    <a href="#" class="ng2-smart-action ng2-smart-action-edit-save" [innerHTML]="grid.getSetting('edit.saveButtonContent')" (click)="onSave(row, $event)"></a>
    <a href="#" class="ng2-smart-action ng2-smart-action-edit-cancel" [innerHTML]="grid.getSetting('edit.cancelButtonContent')" (click)="row.isInEditing = false;"></a>
  </td>
  <td *ngIf="!row.isInEditing && grid.showActionColumn('right')" class="ng2-smart-actions">
    <button><a href="#" *ngIf="grid.getSetting('actions.edit')" class="ng2-smart-action ng2-smart-action-edit-edit" [innerHTML]="grid.getSetting('edit.editButtonContent')" (click)="onEdit(row, $event)"></a></button>
    <button><a href="#" *ngIf="grid.getSetting('actions.delete')" class="ng2-smart-action ng2-smart-action-delete-delete" [innerHTML]="grid.getSetting('delete.deleteButtonContent')" (click)="onDelete(row, $event)"></a></button>
    <button><a href="#" *ngIf="grid.getSetting('actions.activate')" class="ng2-smart-action ng2-smart-action-delete-delete" [innerHTML]="grid.getSetting('activate.activateButtonContent')" (click)="onActive(row, $event)"></a></button>
  </td>
  <td>Yogesh</td>
</tr>

<tr *ngIf="grid.getRows().length == 0">
  <td [attr.colspan]="grid.getColumns().length + (grid.getSetting('actions.add') || grid.getSetting('actions.edit') || grid.getSetting('actions.delete'))">test {{ grid.getSetting('noDataMessage') }}</td>
</tr>

</tbody>

EN

回答 1

Stack Overflow用户

发布于 2017-02-22 22:18:09

您的方法调用getCustomerItemList()在创建Ng2SmartTable组件时尚未完成,我认为这就是错误消息的原因。我建议如下:

代码语言:javascript
复制
<ng2-smart-table *ngIf="source" [settings]="settings" [source]="data" [defaultSettings]="defaultSettings" [customerDetailsItem]="customerDetailsItem"></ng2-smart-table>  

通过*ngIf,您的组件只会被创建,如果您的可观察性已经完成,并且源不再是未定义的。

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

https://stackoverflow.com/questions/42230293

复制
相关文章

相似问题

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