我已经完成了获取数组的搜索,然后在输入时过滤了它的名称。如果我写static,一切都很好:
export class AddComponent {
protected dataService: CompleterData;
protected searchData = [
{name: '84A4DA'},
{name: '846ASD'},
{name: '8444AS'},
]
constructor(private completerService: CompleterService, private router: Router, public back: BackService,
) {
this.dataService = completerService.local(this.searchData, 'name', 'name');
}
但是当我尝试从db firebase中创建searchData时:
getArray(): void {
this.afDatabase.list('/imones')
.valueChanges()
.subscribe(res => {
console.log(res)//should give you the array of percentage.
this.array = res;
})
}
this.searchData = this.back.getArray();
constructor(private completerService: CompleterService, private router: Router, public back: BackService,
) {
this.dataService = completerService.local(this.searchData, 'name', 'name');
}
我收到错误消息:
如何解决?
答案 0 :(得分:1)
问题在于,在构造函数中,this.SearchData不是数组。原来如此。 1.-您的服务必须可观察到。不订阅服务 2.-将代码从构造函数移动到ngInit 3.-在订阅函数中,您具有searchData的值
很难为我理解您的代码,但是,如果您的服务返回Observables-而不是data-,我相信您的组件可以像
constructor(private completerService: CompleterService,
private router: Router, public back: BackService){}
ngOnInit()
{
this.back.getArray().subscribe(res=>{
this.searchData=res;
completerService.local(this.searchData, 'name', 'name').subscribe(res=>
{
this.dataService=res;
});
})
}
//Or , better, using switchMap
ngOnInit()
{
this.back.getArray().pipe(switchMap(res=>{
this.searchData=res;
return completerService.local(this.searchData, 'name', 'name')
}))
.subscribe(res=>
{
this.dataService=res;
});
}
答案 1 :(得分:-1)
getArray()方法不返回任何数组,但是当您订阅afDatabase.list时,您将获得一个我假定的值数组,因此在subscription回调中,应将值分配给您的数组。
getArray(): void {
this.afDatabase.list('/imones')
.valueChanges()
.subscribe(res => {
console.log(res)//should give you the array of percentage.
this.searchData = res;
})}
或者如果您正在逐一获取值,请写
getArray(): void {
this.afDatabase.list('/imones')
.valueChanges()
.subscribe(res => {
console.log(res)//should give you the array of percentage.
this.searchData.push(res); //searchData must be initialized as empty array
})
}