I'm an Angular and rxjs beginner and in my app I have a form control with mat-autocomplete from https://material.angular.io/components/autocomplete/overview.
On each valueChanges event of that control I want to send an api call which should return an array of data to be displayed as mat-autocomplete options. The problem is that in order to do this I need to return api's response of type Observable<ApiResponseData>
as an Array<MaterialData>
inside of my filtering function.
So far I'm listening to valueChanges where Array<MaterialData>
is expected.
this.filteredMaterialData = this.orderPositionFormGroup.controls['materialId'].valueChanges.pipe(
map(
value => {
if (value.length < 3) {
return []
} else {
return this.filterMaterial(value)
}
}
)
);
filterMaterial
function looks like this and is incorrect because backendFilteredData
is returned before being assigned inside of subscription.
private filterMaterial(name: string): Array<MaterialData> {
this.isLoading = true;
let backendFilteredData: Array<MaterialData> = [];
this.materialService.getMaterialsByName(name).subscribe(
data => {
backendFilteredData = data.content;
this.isLoading = false;
}
)
return backendFilteredData
}
And this is how materialService
looks like.
public getMaterialsByName(name: string): Observable<ApiResponseData> {
const headers: HttpHeaders = new HttpHeaders(
{
"Content-Type": "application/json; charser=utf-8"
}
);
const params: HttpParams = new HttpParams()
.set('page', 0)
.set('size', 500)
.set('sort', "name,asc");
const body = {
logic: "and",
cond: [
{
field: "name",
operator: "ilike",
format: "",
value: "%" + name + "%"
}
]
};
return this.http.post<ApiResponseData>(`${environment.backendHost}/material/lite/filter`, body, {
headers: headers,
params: params
});
}
Knowing that ApiResponseData.content
contains desired Array<MaterialData>
how can I modify my code to be able to return that api reponse as a filterMaterial
function result?