我是一个新的Angular应用,我正在用Angular 10构建一个应用,我的目标是从我的Api中获取一个JSON对象(测试用的假对象),然后根据用户输入的内容来过滤结果。
实际上,当页面刷新时,对API的调用已经完成(只有一次),结果是确定的,命名空间也显示出来了,但是当我点击命名空间的名字时,它显示的是[object Object]而不是名字:)
服务-命名空间.组件.ts
import { Component, OnInit } from '@angular/core';
import { RestApiService } from '../shared/rest-api.service';
import { FormControl } from '@angular/forms';
import { Observable, of, Subscription } from 'rxjs';
import { tap, startWith, debounceTime, switchMap, map, filter } from 'rxjs/operators';
@Component({
selector: 'app-services-namespace',
templateUrl: './services-namespace.component.html',
styleUrls: ['./services-namespace.component.scss']
})
export class ServicesNamespaceComponent implements OnInit {
myControl = new FormControl();
options = [];
filteredOptions: Observable<any[]>;
constructor(private dataService: RestApiService) {}
ngOnInit() {
this.filteredOptions = this.myControl.valueChanges.pipe(
startWith(''),
debounceTime(400),
switchMap(value => this.doFilter(value))
)
}
doFilter(value) {
return this.dataService.getAllNameSpaces()
.pipe(
map(response => response.filter(option => {
return option.namespace.toLowerCase().indexOf(value.toLowerCase()) === 0
}))
)
}
}
服务-命名空间.组件.html
<form class="example-form">
<mat-form-field class="example-full-width">
<input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let option of filteredOptions | async" [value]="option">
{{option.namespace}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>
Json结果。
[
{
namespace: "p6-d2"
},
{
namespace: "p1-d"
},
{
namespace: "p0-q"
},
{
namespace: "p2-p"
}
]
我们的目标是所有的结果都显示在这个搜索栏中,当用户在里面录入一些东西时,它就会对结果进行过滤.我希望只需要做一次调用(因为这个调用将检索所有的东西),然后我们就可以过滤所有时间的相同的Json对象.感谢帮助一个新手!
代码编辑
在HTML方面 -> 替换为
<mat-autocomplete #auto="matAutocomplete" [displayWith]="getOptionText">
在服务-命名空间方面。
getOptionText(option) {
return option.namespace;
}