我通过以下过程加载 Firestore 数据库中文档字段的值:
let currentUser = firebase.auth().currentUser;
this.afs.collection("people").doc(currentUser.uid).get().subscribe( opportunities => {
this.items = opportunities.get("following");
});
然后我使用 this.items 来过滤 html 中加载的即时搜索数据。我通过在 js 代码中定义以下配置来实现此目的(请注意,我引用 this.items 作为过滤器。
this.config = {
...environment.algolia,
indexName: 'test',
searchParameters: {
disjunctiveFacetsRefinements: {
poster: this.items
}
},
routing: {
router: historyRouter(),
stateMapping: {
stateToRoute({query, page}) {
return {
query: query,
page: page
};
},
routeToState({query, page}) {
return {
query: query,
page: page
};
}
}
}
}
然后在我的 html 中,我按如下方式引用此配置对象:
<ais-instantsearch [config]="config">
但问题是,在我定义 this.items 的过程成功完成之前,html 正在加载此配置文件。我知道这是因为它是从我的数据库中提取的异步进程,但我不知道如何解决它。我尝试将 this.config 的声明添加到代码的 opportunity => {} 部分中,以便在获得 this.items 值后发生;然而,html 仍然加载,然后失败,因为配置尚未定义。解决这个问题的好方法是什么?
最佳答案
我建议使用异步管道解决配置。
<ais-instantsearch [config]="config | async">
这需要将 this.config
设为可观察对象,我建议使用BehaviorSubject:http://reactivex.io/RxJava/javadoc/rx/subjects/BehaviorSubject.html
private readonly config: BehaviorSubject<any> = new BehaviorSubject(undefined);
# ...
ngOnInit() {
let currentUser = firebase.auth().currentUser;
this.afs.collection("people").doc(currentUser.uid).get()
.subscribe(opportunities => {
let items = opportunities.get("following");
let config = {
...environment.algolia,
indexName: 'test',
searchParameters: {
disjunctiveFacetsRefinements: {
poster: items
}
},
routing: {
router: historyRouter(),
stateMapping: {
stateToRoute({ query, page }) {
return {
query: query,
page: page
};
},
routeToState({ query, page }) {
return {
query: query,
page: page
};
}
}
}
};
this.config.next(config);
});
}
关于javascript - 等待加载 html,直到从异步进程加载引用的 js 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56081840/