如何在从FormGroup获取请求主体时使用md-table的Http POST响应数据?

时间:2017-07-26 06:55:47

标签: angular typescript angular-material

我跟随retrieving data through http的掠夺者。我想使用FormControl在POST请求正文中使用输入字段,并在md-table中显示响应。

我的问题是ExampleDatabase和ExampleDatabaseSource是单独的类。我知道如何使用单独的服务在组件中定期执行http POST请求,但我不知道如何将POST主体传递给ExampleDatabase进行Http调用或将完成的服务响应传递给ExampleDatabase以便我可以在表格中显示?

我创建了一个我的意思的示例组件:

import {Component} from '@angular/core';
import {Http, Response} from '@angular/http';
import { FormControl, FormGroup, Validators, FormBuilder } from '@angular/forms';
import {DataSource} from '@angular/cdk';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/observable/merge';
import 'rxjs/add/operator/map';

import {TestService} from './service'

@Component({
  selector: 'md-table-question',
  templateUrl: 'md-table-question.html',
})
export class MdTableQuestion {

  displayedColumns = ['id'];
  exampleDatabase: ExampleDatabase | null;
  dataSource: ExampleDataSource | null;
  form: FormGroup;

  constructor(private _testService: TestService, private _fb: FormBuilder) {
    this.exampleDatabase = new ExampleDatabase();
    this.dataSource = new ExampleDataSource(this.exampleDatabase);
  }
  ngOnInit() {
        this.form = this._fb.group({
            name:['', Validators.compose([
                Validators.required
                ])],
                ]},      
      );

// Here is the submit form that sends POST request. It comes from an ngSubmit event:
  submitForm(){
    let body= {name:this.form.get('name').value}
    this._testService.testRequest(body)
          .subscribe(res => {
            console.log(res);
          })
  }
}
export interface test {
   id: number;
}

export class ExampleDatabase {
  dataChange: BehaviorSubject<test[]> = new BehaviorSubject<test[]>([]);
  get data(): test[] {
// Not sure how to get data to here 
    // let data = 
    // return data;
  }
  constructor() {
    this.dataChange.next(this.data);
  }
};

export class ExampleDataSource extends DataSource<any> {
  constructor(private _exampleDatabase: ExampleDatabase) {
    super();
  }
  connect(): Observable<test[]> {
    return this._exampleDatabase.dataChange;
  }
  disconnect() {}
}
}

任何有关如何做到这一点的帮助都很棒

更新

以下是问题的plnkr

1 个答案:

答案 0 :(得分:0)

我想做的一个快速建议是,您使用service就像一个真正的服务,并实现它的mock版本,为您的应用程序提供示例数据测试和实施目的。

interface IExampleService {
    get(id: number): Observable<ExampleResult>
}

@Injectable() ExampleService implements IExampleService {
    get(id: number): Observable<ExampleResult> {
       return Observable.of( {} ) // empty object
    }
}

@Injectable() MockExampleService implements IExampleService {
    get(id: number): Observable<ExampleResult> {
       return blablabla // Return an observable with your expected test data.
    }
}

然后,您可以在模块providers部分中切换它,以加载模拟而不是实际服务。