如何在从 FormGroup 获取请求正文的同时将 Http POST 响应数据用于 md-table?



我遵循了通过http检索数据的plunker。我想使用 FormControl 在请求正文中使用输入字段POST并在md-table中显示响应。

对我来说,问题是示例数据库和示例数据库源是单独的类。我知道如何使用单独的服务在组件中执行常规的 httpPOST请求,但我不知道如何将 POST 正文传递给示例数据库以进行 Http 调用或将完成的服务响应传递给示例数据库以便我可以显示在表中?

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

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

我想做的一个快速建议是,你像使用真正的服务一样使用你的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部分中切换它以加载模拟而不是实际服务。

相关内容

最新更新