Angular 4 Material http服务未被调用

时间:2017-11-03 10:32:27

标签: angular rest angular-material2

我试图从其他服务器上运行的角度调用我的休息服务,并使用角度材料填充表格,我已经完成了如何使用Angular 4和Angular 4材质表中的服务md-table不在下面的程序中尝试填充

组件:

import { MatPaginator } from '@angular/material';
import { DataSource } from '@angular/cdk/collections';
import { Component, OnInit,ViewChild,ChangeDetectorRef } from '@angular/core';
import { WellService } from '../services/well.service';
import { Well } from '../well/well';
import {  Observable  } from 'rxjs/Rx';
import { BehaviorSubject } from  'rxjs/BehaviorSubject';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/observable/merge';
import 'rxjs/add/operator/map';



@Component({
  selector: 'app-well',
  templateUrl: './well.component.html',
  styleUrls: ['./well.component.css'],
  providers:[WellService]
})



export class WellComponent implements OnInit {
  title = 'Wells';
  header:string;
  displayedColumns = ['active', 'company', 'country', 'well','wellbore'];
  public wellDatabase : WellDatabase | any;
  public wellDataSource: WellDataSource | any;

  @ViewChild(MatPaginator) paginator : MatPaginator;

  constructor(private wellService:WellService,private changeDetector:ChangeDetectorRef) {

    this.header='assets/images/BHI_header_logo_bd.png'  

   }

  ngOnInit() {
    this.wellDataSource = new WellDataSource(this.wellDatabase,this.paginator);
    this.changeDetector.detectChanges();
    console.log(this.wellDataSource);
  }

}
export class WellDatabase  {

  dataChange: BehaviorSubject<Well[]> = new BehaviorSubject<Well[]>([]);
  get data(): Well[] { return this.dataChange.value }

  constructor(private wellService: WellService) {
    this.getWells();
  }
getWells(){
  this.wellService.getWells().subscribe( response => {
    this.dataChange.next(response);
});
}






}
export class WellDataSource extends DataSource<any> {

  constructor(private _wellDatabase : WellDatabase, private _paginator: MatPaginator){
    super();
  }

  connect(): Observable<Well[]> {

const displayDataChanges = [
      this._wellDatabase.dataChange,
      this._paginator.page
    ];
    return Observable.merge(...displayDataChanges).map(() => {
      const data = this._wellDatabase.data.slice();
      const startIndex = this._paginator.pageIndex * this._paginator.pageSize;
      return data.splice(startIndex, this._paginator.pageSize);
    })
  }

  disconnect() {}
}  

服务

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response  } from '@angular/http';
import { Observable,Subject } from 'rxjs/Rx';
import 'rxjs/add/operator/toPromise';  
import { Well } from '../well/well';
import 'rxjs/Rx';
@Injectable()
export class WellService {


  constructor(private  http:Http) { }
public getWells(): Observable < Well[] > {  
    return this.http.get('http://localhost:8080/RESTfulExample/rest/auth/testuser1/pass').map((response: Response) => {  
        return <Well[] > response.json().wellList;  
    }).catch(this.handleError);  
}  
//    
private handleError(errorResponse: Response) {  
    console.log(errorResponse.statusText);  
    return Observable.throw(errorResponse.json().error || "Server error");  
}  
private getHeaders(){
    // I included these headers because otherwise FireFox
    // will request text/html instead of application/json
    let headers = new Headers();
    headers.append('Accept', 'application/json');
    return headers;
  }

}

HTML:

<div style="text-align:center">  
  <div><img width="1100" [src]="header" margin-top:-40px></div>
   <div> 
        <mat-table #table [dataSource]="dataSource">



    <!-- Active -->
    <ng-container matColumnDef="active">
      <mat-header-cell *matHeaderCellDef> Active </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.well.active}} </mat-cell>
    </ng-container>

    <!-- Company -->
    <ng-container matColumnDef="company">
      <mat-header-cell *matHeaderCellDef> Company </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.company}} </mat-cell>
    </ng-container>

    <!-- Country -->
    <ng-container matColumnDef="country">
      <mat-header-cell *matHeaderCellDef>Country</mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.well.country}} </mat-cell>
    </ng-container>

    <!-- Well -->
    <ng-container matColumnDef="well">
      <mat-header-cell *matHeaderCellDef> Well </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.well}} </mat-cell>
    </ng-container>


        <!-- Wellbore -->
        <ng-container matColumnDef="wellbore">
          <mat-header-cell *matHeaderCellDef> Wellbore </mat-header-cell>
          <mat-cell *matCellDef="let row"> {{row.well.wellbore}} </mat-cell>
        </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
  </mat-table>


  <mat-paginator #paginator
  [length]="wellDataSource.length"
  [pageIndex]="0"
  [pageSize]="25"
  [pageSizeOptions]="[5, 10, 25, 100]">
</mat-paginator>



          </div>           
</div>  

我能够看到我的HTTP服务没有被调用,我遵循的程序是否正确可以在这方面指导我。

json响应如下所示: {&#34; wellList&#34;:[{&#34; country&#34;:&#34; USA&#34;,&#34; well&#34;:&#34; HBASE WELL&#34;,& #34;井筒&#34;:&#34; HBASE WELLBORE&#34;,&#34;公司&#34;:&#34; BAKER HUGHES&#34;,&#34;活跃&#34;:&#34; -1&#34;},{&#34;国家&#34;:&#34;美国&#34;&#34;以及&#34;:&#34; CurveEntWell&#34;&#34;井筒&# 34;:&#34; CurveEntWellBore&#34;,&#34;公司&#34;:&#34; BAKER HUGHES&#34;,&#34;活跃&#34;:&#34; -1&#34;} ,{&#34;国家&#34;:&#34;美国&#34;&#34;以及&#34;:&#34; 20Feb17Well&#34 ;, &#34;井筒&#34;:&#34; 20Feb17Wellbore2&#34;,&#34;公司&#34;:&#34; BAKER HUGHES&#34;,&#34;活跃&#34;:&#34; -1&#34;}]}

2 个答案:

答案 0 :(得分:1)

你过度复杂,你不需要WellDatabase因为我们得到了“真实”的数据。所以你要做的是获取组件中的数据,将其存储在一个observable中,并将该observable传递给WellDataSource

请比我在下面更好地命名(和键入)变量;)

public dataSource: WellDataSource | any;
obs: any;

ngOnInit() {
  this.obs = this.wellService.getWells();
  this.dataSource = new WellDataSource(this.obs, this.paginator);
}

然后是您的WellDataSource

constructor(private _obs: any, private _paginator: MatPaginator) {
  super();
}

connect(): Observable<any[]> {
  const displayDataChanges = [
    this._obs,
    this._paginator.page,
  ];

  return this._obs.flatMap(x => {
    return Observable.merge(...displayDataChanges).map(() => {
      const data = x.slice();
      const startIndex = this._paginator.pageIndex * this._paginator.pageSize;
      return data.splice(startIndex, this._paginator.pageSize);
    });
  })
}

你的html也有错误,应该是

[length]="dataSource._obs.value.length"

而不是

[length]="wellDataSource.length"

<强> https://github.com/facebook/facebook-php-ads-sdk

答案 1 :(得分:0)

试试这个示例代码

//Component
getWells(){
    this.wellService.getWells()
          .then(data => {

            if (verifyResponse(data)) {
              // Success case area
              this.dataChange.next(response);
            } else {
              //Negative case area need to handle here
            }
          });
}

//Method to verify response data
verifyResponse(data){
    // verfiy accordingly and return flags
    if(){
        return true;
    }else{
        return false;
    }
}

//Service
getWells(){
        return new Promise(resolve => {
           this.http.get('http://localhost:8080/RESTfulExample/rest/auth/testuser1/pass' )
                    .subscribe(
                        data => {
                            resolve(data.wellList);                                 
                        }, error => {
                            resolve(false);                               
            });

        });
}