【发布时间】:2017-11-16 12:07:33
【问题描述】:
我的服务 TranslatorService 的构造函数中的这段代码有什么方法可以为所有应用程序或按需调用一次,而不是所有时间加载 homecomponent ????
this.translations$ = translationsCollection.snapshotChanges().map(actions => {
return actions.map(a => {
...
})
我从 firestore ex 中检索的翻译类:
{
"WELCOME": {
"FR": "bienvenue",
"GB": "Welcome"
}
}
export interface Translation {
[code: string]: TranslationInfo;
}
export interface TranslationInfo {
[language: string]: string;
}
我的核心模块
import { NgModule } from '@angular/core';
import { AuthService } from './auth.service';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { AngularFirestoreModule } from 'angularfire2/firestore';
import { TranslatorService } from '../services/translator.service';
@NgModule({
imports: [
AngularFireAuthModule,
AngularFirestoreModule
],
providers: [AuthService, TranslatorService]
})
export class CoreModule { }
在应用模块中注入
@NgModule({
declarations: [
...
],
imports: [
...
CoreModule,
...
],
providers: [AuthGuard],
bootstrap: [AppComponent]
})
export class AppModule { }
我的翻译服务
@Injectable()
export class TranslatorService {
translationsCollection: AngularFirestoreCollection<Translation>;
translations$: Observable<any>;
public translations: Translation[];
constructor(private afs: AngularFirestore) {
var translationsCollection = this.afs.collection("translations");
this.translations$ = translationsCollection.snapshotChanges().map(actions => {
return actions.map(a => {
...
})
});
我的组件
export class HomeComponent implements OnInit {
translations$: Observable<any>;
constructor(private translator: TranslatorService) { }
ngOnInit() {
this.translations$ = this.translator.translations$;
}
我的组件视图
<div *ngFor="let translation of translations$|async">
<pre>{{translation | json}}</pre>
</div>
【问题讨论】:
标签: rxjs observable angularfire2 google-cloud-firestore