我已经为保存的收藏创建了一个服务和一个界面。 我的收藏集包含3个字段:id,title,tags [],它是一个字符串数组。我使用集合快照获取ID,并使用名为getSaved的方法获取保存的标题。 我如何获取标签数组的元素以便将其显示到我的html文件中。
//saved interface
export interface Saved {
id: string;
title: string;
tags: string[];
}
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { AuthService } from './auth.service';
import { LoadingService } from './loading.service';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from '@angular/fire/firestore';
import { AngularFireStorage } from '@angular/fire/storage';
import { Saved } from '../interfaces/Saved';
import { firestore } from 'firebase';
@Injectable({
providedIn: 'root'
})
export class SavedService {
savedCollections: AngularFirestoreCollection<Saved>;
saved: Observable<any>;
constructor(
public db: AngularFirestore,
private loadingService: LoadingService
) {
// this.saved = this.db.collection('saved').valueChanges();
// Use snapshot instead to have access to id
this.saved = this.db.collection('saved').snapshotChanges().map(changes => {
return changes.map(a => {
const data = a.payload.doc.data() as Saved;
data.id = a.payload.doc.id;
return data;
})
});
}
getSaved() {
return this.saved;
}
}
// saved.component.ts
import { Component, OnInit } from '@angular/core';
import { AuthService } from 'src/app/services/auth.service';
import { LoadingService } from 'src/app/services/loading.service';
import { ActivatedRoute } from '@angular/router';
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';
import { Subscription } from 'rxjs/Subscription';
import { SavedService } from '../../services/saved.service';
import { Saved } from 'src/app/interfaces/Saved';
@Component({
selector: 'app-savedchats',
templateUrl: './savedchats.component.html',
styleUrls: ['./savedchats.component.scss']
})
export class SavedchatsComponent implements OnInit {
public saved: Saved[];
private subscriptions: Subscription[] = [];
constructor(
// Adding saved service
private savedService: SavedService,
private auth: AuthService,
private loadingService: LoadingService,
private route: ActivatedRoute,
private db: AngularFirestore
) {
// this.loadingService.isLoading.next(true);
}
ngOnInit() {
// Add elemetns from db using savedService
this.savedService.getSaved().subscribe( saved => {
this.saved = saved;
console.log(saved);
});
}
}
答案 0 :(得分:1)
您是否正在寻找类似的东西?
this.saved = this.db.collection('saved').snapshotChanges().map(changes => {
return changes.map(a => {
const data = a.payload.doc.data() as Saved;
data.id = a.payload.doc.id;
return data;
});
}).sort((stra, strb) => (stra < strb ? -1 : 1));
还是像这样的数组外部元素?
let list = [];
this.saved = this.db.collection('saved').snapshotChanges().map(changes => {
return changes.map(a => {
const data = a.payload.doc.data() as Saved;
data.id = a.payload.doc.id;
list.push(data.id).sort((stra, strb) => (stra < strb ? -1 : 1));
return data;
});
});