使用 api 调用使有角度的材料表正常工作 [英] getting angular material table to work properly with api call

查看:24
本文介绍了使用 api 调用使有角度的材料表正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让 Angular 材料表与对我的数据库的 api 调用一起使用我得到正确的数据我只想用新的材料表显示,但由于某种原因,这没有按预期工作.

这是我的主要组件

import { Component } from '@angular/core';从 './app.aos.service.component' 导入 {AosService}从 './QuoteModel' 导入 {QuoteModel}从 '@angular/cdk' 导入 {DataSource};@成分({选择器:'app-aos',提供者:[AosService],templateUrl: './app.aos.quoteQuery.component.html',styleUrls: ['./app.aos.quoteQuery.component.scss']})导出类 AOSAppComponent {displayColumns = ['OrdNbr', 'sotypeid', 'user6', 'LUpd_DateTime', 'User3', 'crtd_user', 'S4Future01', 'SlsperID', 'TotMerch', 'CustOrdNbr'];数据源;公开数据;公共 hidData = 真;构造函数(私有_aosService:AosService){}getAosQuote(报价:字符串){this._aosService.getQuoteQueryData(quote.toUpperCase()).subscribe(res => {this.hidData = false;this.DataSource = res.recordset;console.log(this.DataSource);})}}

这是我的服务模块进行调用

import { Injectable } from '@angular/core';从'@angular/http'导入{标题,Http,RequestOptions};导入 'rxjs/add/operator/map';导入 'rxjs/add/operator/catch';从 'rxjs/Rx' 导入 { Observable };从 './QuoteModel' 导入 {QuoteModel}@Injectable()导出类 AosService {private headers = new Headers({ 'content-type': 'application/json', 'Accept': 'application/json' });private options = new RequestOptions({ headers: this.headers });private aosUrl = 'http://localhost:3001/api/query/'构造函数(私有http:Http){}getQuoteQueryData(报价:字符串){返回 this.http.get(this.aosUrl + quote, this.options).map((res: any) => res.json()).catch((error: Response) => [{ status: error }]);}}

我正在我的 console.log 语句中取回数据

这是我的 html

解决方案

您在评论中提供的代码是正确的.要将quote 传递给服务,您需要在AOSDataSource 类的constructor 中添加一个附加参数.然后,您可以在从 getAosQuote 函数创建 AOSDataSource 实例时从组件传递 quote 值.

Plunker 演示

ts:

导出类 AOSAppComponent {displayColumns = ['OrdNbr', 'sotypeid', 'user6', 'LUpd_DateTime', 'User3', 'crtd_user', 'S4Future01', 'SlsperID', 'TotMerch', 'CustOrdNbr'];数据源:AOSDataSource |空值;tableVisible = false;构造函数(私有应用状态:AppState){}getAosQuote(报价:字符串,keepFocus:布尔值){如果(!this.tableVisible){setTimeout(() => {document.getElementById('quote').blur();如果(保持焦点){document.getElementById('quote').focus();}this.tableVisible = true},2000)}this.dataSource = new AOSDataSource(this.appState, quote);}}导出类 AOSDataSource 扩展了 DataSource{构造函数(私有应用程序状态:AppState,私有引用:字符串){极好的();}主题:行为主题<[]>= new BehaviorSubject<[]>([]);connect(): Observable<[]>{console.log('connect');如果(!this.subject.isStopped)this.appState.getQuoteQueryData(this.quote.toUpperCase()).订阅({下一个:(值)=>{控制台日志(值);this.subject.next(value);}});返回 Observable.merge(this.subject);}断开连接(){this.subject.complete();this.subject.observers = [];}}

注意:我在 getAosQuote 函数中添加了一个额外的 boolean 标志和 setTimeout 因为我遇到了问题,在初始化之后,该表需要几秒钟和一个事件来触发 connect() 并呈现数据.因此,我将其添加为一种解决方法.

I am trying to get Angular material table to work with an api call to my database I get the right data I just want to display with the new material table and for some reason this is not working as expected.

this is my main component

import { Component } from '@angular/core';
import {AosService} from './app.aos.service.component'
import {QuoteModel} from './QuoteModel'
import {DataSource} from '@angular/cdk';

@Component({
  selector: 'app-aos',
  providers: [AosService],
  templateUrl: './app.aos.quoteQuery.component.html',
  styleUrls: ['./app.aos.quoteQuery.component.scss']
})
export class AOSAppComponent {
    displayedColumns = ['OrdNbr', 'sotypeid', 'user6', 'LUpd_DateTime', 'User3', 'crtd_user', 'S4Future01', 'SlsperID', 'TotMerch', 'CustOrdNbr'];
    DataSource;
    public datas;
    public hidData = true;

    constructor(private _aosService: AosService) {

    }

    getAosQuote(quote: string) {
      this._aosService.getQuoteQueryData(quote.toUpperCase()).subscribe(res => {
        this.hidData = false;
       this.DataSource = res.recordset;
        console.log(this.DataSource);
      })  
    }
}

this is my service module making the call

import { Injectable } from '@angular/core';
import { Headers, Http, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { Observable } from 'rxjs/Rx';
import {QuoteModel} from './QuoteModel'

@Injectable()
export class AosService {
    private headers = new Headers({ 'content-type': 'application/json', 'Accept': 'application/json' });
    private options = new RequestOptions({ headers: this.headers });
    private aosUrl = 'http://localhost:3001/api/query/'

    constructor(private http: Http) { }

    getQuoteQueryData(quote: string) {
        return this.http.get(this.aosUrl + quote, this.options)
            .map((res: any) => res.json())
            .catch((error: Response) => [{ status: error }]);
    }
}

I am getting data back in my console.log statement

this is my html

<app-aos-header></app-aos-header>
<div class="container">
    <div>
        <md-input-container class="aos-full-width">
            <input type="search" (keyup.enter)="getAosQuote(quote.value)" #quote mdInput placeholder="Quote Number" required>
        </md-input-container>
    </div>
    <div>
        <button md-raised-button color="primary" (click)="getAosQuote(quote.value)" type="button">Search</button>
    </div>
</div>
<div [hidden]="hidData" class="example-container mat-elevation-z8">
    <md-table #table [dataSource]="dataSource">

        <ng-container cdkColumnDef="CustOrdNbr">
            <md-header-cell *cdkHeaderCellDef> Customer Order Number </md-header-cell>
            <md-cell *cdkCellDef="let row"> {{row.CustOrdNbr}} </md-cell>
        </ng-container>

        <ng-container cdkColumnDef="LUpd_DateTime">
            <md-header-cell *cdkHeaderCellDef> Last Update </md-header-cell>
            <md-cell *cdkCellDef="let row"> {{row.LUpd_DateTime}}% </md-cell>
        </ng-container>

        <ng-container cdkColumnDef="OrdNbr">
            <md-header-cell *cdkHeaderCellDef> Order Number </md-header-cell>
            <md-cell *cdkCellDef="let row"> {{row.OrdNbr}} </md-cell>
        </ng-container>

        <ng-container cdkColumnDef="S4Future01">
            <md-header-cell *cdkHeaderCellDef>Future</md-header-cell>
            <md-cell *cdkCellDef="let row">{{row.S4Future01}} </md-cell>
        </ng-container>

        <ng-container cdkColumnDef="SlsperID">
            <md-header-cell *cdkHeaderCellDef>Sales person</md-header-cell>
            <md-cell *cdkCellDef="let row">{{row.SlsperID}} </md-cell>
        </ng-container>

        <ng-container cdkColumnDef="TotMerch">
            <md-header-cell *cdkHeaderCellDef>Total Merchandise</md-header-cell>
            <md-cell *cdkCellDef="let row">{{row.TotMerch}} </md-cell>
        </ng-container>

        <ng-container cdkColumnDef="User3">
            <md-header-cell *cdkHeaderCellDef>User 3</md-header-cell>
            <md-cell *cdkCellDef="let row">{{row.User3}} </md-cell>
        </ng-container>

        <ng-container cdkColumnDef="crtd_user">
            <md-header-cell *cdkHeaderCellDef>crtd_user</md-header-cell>
            <md-cell *cdkCellDef="let row">{{row.crtd_user}} </md-cell>
        </ng-container>

        <ng-container cdkColumnDef="sotypeid">
            <md-header-cell *cdkHeaderCellDef>SO Type</md-header-cell>
            <md-cell *cdkCellDef="let row">{{row.sotypeid}} </md-cell>
        </ng-container>

        <ng-container cdkColumnDef="user6">
            <md-header-cell *cdkHeaderCellDef>user 6</md-header-cell>
            <md-cell *cdkCellDef="let row">{{row.user6}} </md-cell>
        </ng-container>

        <md-header-row *cdkHeaderRowDef="displayedColumns"></md-header-row>
        <md-row *cdkRowDef="let row; columns: displayedColumns;"></md-row>
    </md-table>
</div>

I am getting my table headers but no data in the cdkCellDef

解决方案

You are on right track with the code you provided in the comments. To pass the quote to service, you need add an addition parameter to the constructor of AOSDataSource class. Then you can pass the quote value from your component when created the instance of AOSDataSource from getAosQuote function.

Plunker demo

ts:

export class AOSAppComponent {

  displayedColumns = ['OrdNbr', 'sotypeid', 'user6', 'LUpd_DateTime', 'User3', 'crtd_user', 'S4Future01', 'SlsperID', 'TotMerch', 'CustOrdNbr'];
  dataSource: AOSDataSource | null;

  tableVisible = false;

  constructor(private appState: AppState){ }

  getAosQuote(quote: string, keepFocus: boolean) {

    if(!this.tableVisible){
     setTimeout(() => { 
        document.getElementById('quote').blur();
        if(keepFocus){
          document.getElementById('quote').focus();
        }
        this.tableVisible = true}, 
      2000) 
    }
    this.dataSource = new AOSDataSource(this.appState, quote);
  }  
}

export class AOSDataSource extends DataSource<any> {
  constructor(private appState: AppState, private quote: String) {
    super();
  }

  subject: BehaviorSubject<[]> = new BehaviorSubject<[]>([]);

  connect(): Observable<[]> {
      console.log('connect');
      if (!this.subject.isStopped)
          this.appState.getQuoteQueryData(this.quote.toUpperCase())
              .subscribe({
                next: (value) => {
                  console.log(value);
                  this.subject.next(value);
                }
              });
      return Observable.merge(this.subject);
  }

  disconnect() {
      this.subject.complete();
      this.subject.observers = [];
  }
}

Note: I added an extra boolean flag and setTimeout in the getAosQuote function because I was running into problem where, right after initialization, the table requires couple seconds and an event to trigger connect() and render the data. So, I added that as a workaround.

这篇关于使用 api 调用使有角度的材料表正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆