Привет, мне было интересно, можно ли было объединить две службы angular для CRUD определенной коллекции c внутри коллекции. У меня есть домашнее приложение, в котором дом относится к этому пользователю. внутри дома один из компонентов - тодолист. У меня уже есть служба для дома, которая выполняет CRUD для домов. Для тодолиста я создала службу, но меня удивляет, как я собираюсь получить доступ к дому, указанному c для пользователя. Я приложил свой код в минуту ниже, и любые рекомендации будут полезны для меня, чтобы помочь в этой работе. Тодосервис
import { Injectable } from '@angular/core';
import { promise } from 'protractor';
import { DocumentReference, AngularFirestore, AngularFirestoreCollection } from '@angular/fire/firestore';
import { HouseService, House } from './house.service';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import {Todolist} from '../modal/Todolist';
@Injectable({
providedIn: 'root'
})
export class TodoserviceService {
private houses: Observable<House[]>;
private houseCollection: AngularFirestoreCollection<House>;
private todolist: Observable<Todolist[]>;
private todolistCollection: AngularFirestoreCollection<Todolist>;
constructor(houseService : HouseService,
private afs: AngularFirestore) {
this.houseCollection = this.afs.collection<House>('house');
this.houses = this.houseCollection.snapshotChanges().pipe(
map(actions => {
return actions.map(a => {
const data = a.payload.doc.data();
const id = a.payload.doc.id;
return { id, ...data };
});
})
);
}
//Function to retrieve all collection data for house
getAllTodolist(id : string){
this.todolistCollection = this.afs.collection('house').doc(id).collection<Todolist>('todo list');
this.todolist = this.todolistCollection.snapshotChanges().pipe(
map(actions => {
return actions.map(a => {
const data = a.payload.doc.data();
return { id, ...data};
});
})
);
return this.todolist;
}
gettodolist(): Observable<Todolist[]>{
return this.todolist
}
gettodo(id){
return this.houseCollection.doc(id).collection<Todolist>(id).valueChanges();
}
//
//HAVING .COLLECTION('todo').ADD - IF THERE IS NO COLLECTION IT WILL CREATE ONE, IF THERE IS IT WILL ADD TO IT
addTodolist(id: any, todolist: Todolist ): Promise<DocumentReference>{
return this.houseCollection.doc(id).collection('todo list').add(todolist);
}
updateTodolist(id: any, todolist: Todolist): Promise<void>{
return this.houseCollection.doc(id).collection<Todolist>("todo list").doc(id).update({title: todolist.title, description: todolist.description, last_date: todolist.last_date });
}
deleteTodolist(id: any): Promise<void> {
return this.houseCollection.doc(id).collection<Todolist>("todo list").doc(id).delete();
}
}
Addtodo.ts
import { Component, OnInit } from '@angular/core';
import { NavController } from '@ionic/angular';
import { ToastController } from '@ionic/angular';
import { House, HouseService } from '../Services/house.service';
import { ActivatedRoute, Route, Router } from '@angular/router';
import { TodoserviceService } from '../Services/todoservice.service';
import { AngularFirestore } from '@angular/fire/firestore';
import { map } from 'rxjs/operators';
import { Todolist } from '../modal/Todolist';
import { Observable } from 'rxjs';
@Component({
selector: 'app-add-todo',
templateUrl: './add-todo.page.html',
styleUrls: ['./add-todo.page.scss'],
})
export class AddTodoPage implements OnInit {
todolist: Todolist = {
title: '',
description: '',
last_date: '',
}
currentHouse: House;
currentHouseId: string;
constructor(private activatedRoute: ActivatedRoute,
private router: Router,
private route: Router, private navCtrl: NavController,
private toastCtrl: ToastController, private todoserviceService: TodoserviceService,
private houseService: HouseService) {
}
ngOnInit() {
let id1 = this.route.url.split('id=');
let id2 = id1[1].toString();
let id3 = id2.split('/');
let id = id3[0].toString();
this.houseService.getHouse(id);
if (id) {
this.houseService.getHouse(id).subscribe(house => {
this.currentHouse = house;
this.currentHouseId = id;
});
console.log(this.currentHouseId)
}
}
addTodolist() {
this.todoserviceService.addTodolist(this.currentHouseId, this.todolist).then(() => {
this.router.navigateByUrl('/');
}, err => {
});
}
}
HouseService
import { Injectable } from '@angular/core';
import * as firebase from 'firebase/app';
import { map, take } from 'rxjs/operators';
import { Observable } from 'rxjs';
import 'firebase/auth';
import 'firebase/firestore';
import { AngularFirestoreCollection, AngularFirestore, DocumentReference } from '@angular/fire/firestore';
import { THIS_EXPR } from '@angular/compiler/src/output/output_ast';
import { promise } from 'protractor';
//Interface for new house object. It will be created with all of these elements
export interface House {
id?: string,
name: string,
address: string,
eircode: string,
members: string[]
}
@Injectable({
providedIn: 'root'
})
export class HouseService {
//Initialise necessary objects to store results from Firebase DB
private houses: Observable<House[]>;
private houseCollection: AngularFirestoreCollection<House>;
//Initialise firebase and get collection from DB
constructor(private afs: AngularFirestore) {
this.houseCollection = this.afs.collection<House>('house');
this.houses = this.houseCollection.snapshotChanges().pipe(
map(actions => {
return actions.map(a => {
const data = a.payload.doc.data();
const id = a.payload.doc.id;
return { id, ...data };
});
})
);
}
//***HOUSE FUNCTIONS */
//Get all houses from DB
getHouses(): Observable<House[]> {
return this.houses;
}
//Get singular house from DB using ID
getHouse(id: string): Observable<House> {
return this.houseCollection.doc<House>(id).valueChanges().pipe(
take(1), //takes one observable as there is no need to keep constantly updated
map(house => {
house.id;
return house
})
);
}
//Add house object to DB
addHouse(house: House): Promise<DocumentReference> {
return this.houseCollection.add(house);
}
//Update main attribues of house object in DB
updateHouse(house: House): Promise<void> {
return this.houseCollection.doc(house.id).update({ name:house.name, address:house.address, eircode:house.eircode, members:house.members});
}
//Delete house from DB
deleteHouse(id: string): Promise<void> {
return this.houseCollection.doc(id).delete();
}
}