我正在使用模拟数据和 InMemoryDbService,如英雄之旅示例所示。当我不通过 HttpParams 时,加载数据工作正常。添加参数后,我会收到一个 500 响应,正文中出现以下错误:{error: "collection.filter is not a function"}
我已经用 get 请求中的数据填充了我的表,如下所示:
组件代码:
@Component({
selector: 'app-adapter',
templateUrl: './adapter.component.html',
styleUrls: ['./adapter.component.css']
})
export class AdapterComponent implements OnInit {
dataSource = new MatTableDataSource<Request>();
@ViewChild(MatSort) sort: MatSort;
@ViewChild(MatPaginator) paginator: MatPaginator;
constructor(private api: BaseServiceApi) {}
ngOnInit() {
this.refresh(); // this works with no params and populates my table
}
refresh(params?) {
this.getRequests(params)
.subscribe(reply => {
this.dataSource.data = reply.payload as Request[];
this.dataSource.sort = this.sort;
this.dataSource.paginator = this.paginator;
this.pageSize = this.paginator.pageSize;
}
);
}
getRequests(params?): Observable<ServerReply> {
console.log(params);
return this.api.get("requests", params);
}
processSearch() { // here is where I am submitting a form and trying to get new response
if (this.searchForm.invalid)
return;
// these params are not fields of ServerReply or request but are filters
let params = new HttpParams({fromObject: this.searchForm.getRawValue()});
this.refresh(params); // this is submitting with params and throwing exception
}
}
api服务:
import { Injectable } from '@angular/core';
import {Observable, of, pipe} from "rxjs";
import {HttpClient, HttpParams} from "@angular/common/http";
import {catchError} from "rxjs/operators";
import {ServerReply} from "../../models/server-reply";
@Injectable({
providedIn: 'root'
})
export class BaseServiceApi {
apiUrl: string;
constructor(private http: HttpClient) {
}
get(path: string, params?: HttpParams): Observable<ServerReply> {
return this.http.get<ServerReply>(this.apiUrl + path, {params})
//.pipe(catchError(this.handleError<ServerReply>(path, new ServerReply()))
//);
}
private handleError<T>(operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
// TODO: send the error to remote logging infrastructure
console.error(operation + ": " + JSON.stringify(error)); // log to console instead
// Let the app keep running by returning an empty result.
return of(result as T);
};
}
}
服务器回复:
export class ServerReply {
alerts: [];
payload: [];
}
要求:
export class Request {
id: number,
// other fields omitted
}
模拟数据服务:
@Injectable({
providedIn: 'root'
})
export class MockDataService implements InMemoryDbService {
createDb() {
let requests = this.createRequests(1000);
return {requests};
}
private createCloudRequests(count: number) {
// returns one ServerReply with a Request[] in ServerReply.payload
}
}
不知道我做错了什么。我尝试在英雄示例之旅中添加查询参数并且有效(即使英雄的不存在字段也不会像这样出错)。
应用模块导入:
imports: [
BrowserModule,
BrowserAnimationsModule,
FormsModule,
MaterialModule,
AppRoutingModule,
HttpClientModule,
HttpClientInMemoryWebApiModule.forRoot(MockDataService, {dataEncapsulation: false}),
ReactiveFormsModule,
]