Exploring data in Angular 8 and Firebase following the addition of a new item

Currently in my possession:

Two Models:

User.ts

and

Company.ts

I aim to have each User linked to only one company, so that when a user registers, a new company is automatically registered on the firestore table.

The following diagram provides a clearer illustration of my current approach:

https://i.sstatic.net/bVCCz.png

Here is how I initiate the process (within the user registration method from register.component.ts):

this.companyService.addCompany(this.companies, this.user);

And this is the operation of company.service.ts:

export class CompanyService  {
  companiesCollection: AngularFirestoreCollection<Company>;

  constructor(private afs: AngularFirestore,
    private userService: UserService) {
    this.companiesCollection = this.afs.collection('companies',
      ref => ref.orderBy('company_name', 'asc'));
  }

  addCompany(company: Company, user: User) {
    this.companiesCollection.add(company).then(docRef => {
      user.company_id = docRef.id;
      user.uid = localStorage.getItem('userUID');
      this.userService.addUser(user);
    });
  }
}

I believe it would be more effective to implement something like:

addCompany(company: Company): Observable<Company> {
  return this.companiescollection.add(company); // THIS CODE DOESNT WORK
}

Then, utilize the subscription method in register.component.ts, as follows:

this.companyService.addCompany(this.companies).subscribe(companyRef => { this.user.company_id = companyRef.id; this.userService.add(this.user); });

How should I proceed?

Answer №1

Converting the promise into an Observable seems to be the way to go. Simply import {from} from 'rxjs'; and use the following code:


import {from} from 'rxjs';
...
addCompany(company: Company): Observable<Company> {
  return from(this.companiescollection.add(company));
}

Give it a try, this should work for you!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

typescript defining callback parameter type based on callback arguments

function funcOneCustom<T extends boolean = false>(isTrue: T) { type RETURN = T extends true ? string : number; return (isTrue ? "Nice" : 20) as RETURN; } function funcCbCustom<T>(cb: (isTrue: boolean) => T) { const getFirst = () => ...

Combining one item from an Array Class into a new array using Typescript

I have an array class called DocumentItemSelection with the syntax: new Array<DocumentItemSelection>. My goal is to extract only the documentNumber class member and store it in another Array<string>, while keeping the same order intact. Is th ...

"Converting an object array into my own custom type array: A step-by

I have a class: export class Items { id: string; itemName: string; } Previously, when using Angular version less than 4.3, I had this method: getItems(): Observable<Items[]> { return this.http.get('api-url-here/items&ap ...

Learn how to extract precise information from a JSON array by utilizing Angular 6

After making a GET request in Angular 6, I successfully retrieved data from a JSON array. Now, I have this JSON data as an example and my goal is to find the team(s) that employee "TEST4KRWN" is part of. Can anyone guide me on how to write a JSON query us ...

Acquire multiple instances of NestJs dependencies using dependency injection within a single class

Below is a class called Product @Injectable() export class Product { brand: string; } I am injecting the Product class into ProductService export class ProductService { constructor(private readonly product: Product) {} update(products) { ...

Put the Toastr notifications inside a designated container within a particular component

Toastify allows you to set a global container for displaying toasts using the following method: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { BrowserAnimationsModule } from ...

Difficulty with TypeScript when using dynamic keys to reference React components within an object

Typescript is raising an error stating that the expression of type 'string' cannot be used to index the object '{ bg: OverridableComponent<SvgIconTypeMap<{}, "svg">>; de: OverridableComponent<SvgIconTypeMap<{}, &q ...

Is it possible in Angular to generate a module and component without including a CSS file in a single command?

Is it possible to generate a Module linked to a component without automatically creating a css file? For example, the default method I've been using involves: ng generate module name / ng generate component name This results in the typical componen ...

Discovering the highest value within an array of objects

I have a collection of peaks in the following format: peaks = 0: {intervalId: 7, time: 1520290800000, value: 54.95125000000001} 1: {intervalId: 7, time: 1520377200000, value: 49.01083333333333} and so on. I am looking to determine the peak with the hig ...

Is it possible to adjust the font size of every page in Ionic 3 by utilizing the Range feature?

I am struggling with customizing font sizes dynamically using a range slider in my HTML code [settings.html]. <ion-item> <ion-range min="1" max="4" snaps="true" [(ngModel)]="fontSize" class="fontSize"> <ion-label range-left st ...

Unselect all options in Angular's multiple selection feature

Objective: My goal is to ensure that when I invoke the myMethod() function, all options are unselected. Current Issue: Currently, calling myMethod() will only deselect the last option, leaving the others selected if they were previously selected. Possibl ...

Transfer items on a list by dragging and dropping them onto the navigation label of the target component

I'm currently exploring how to move an element from a list to a <div> and then see it transferred to another list. The objective is to allow users to drag items from one list onto the labels in a sidebar navigation, causing the item to switch t ...

Appending an item to an array in TypeScript

I'm feeling lost. I'm attempting to insert new objects into an array in TypeScript, but I encountered an error. My interface includes a function, and I'm puzzled. Can anyone offer guidance? interface Videos{ title: string; descriptio ...

Having trouble with code behaving differently than expected in Chrome's debugger

I've come across a peculiar issue in my TypeScript project (an Angular application). Here's the code snippet that's causing trouble: const idx = myclone.findIndex(x => x.id === action.id); const hasVal = idx>-1; // for some reason, Chr ...

Error: Angular Material module could not be located even after importing additional modules

Encountering an error in angular when trying to import a new material module: ERROR in ./src/app/app.component.ngfactory.js Module not found: Error: Can't resolve '@angular/material/core/index' in 'C:\Users\hrshcse\angul ...

I am attempting to pass input values from a parent component to a child component in order to display them, utilizing the @input decorator

How can I pass input values from a form in the parent component to be displayed in the child component using @Input? Login Form (Parent): <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> & ...

Is there a way to track the loading time of a page using the nextjs router?

As I navigate through a next.js page, I often notice a noticeable delay between triggering a router.push and the subsequent loading of the next page. How can I accurately measure this delay? The process of router push involves actual work before transitio ...

What is the best way to predefine a value for a checkbox in Angular?

Here is the code snippet I am currently using: <input type="checkbox" [(ngModel)]="i.checkt" [ngModelOptions]= {standalone:true} (change)="recovery(i.checkt,i.TherapeuticArea)"> {{i.TherapeuticArea}} I have encountered an issue where setting stan ...

Guide on displaying Angular 6 wildcard page for 404 errors using nginx

After successfully creating an application using Angular 6 and implementing the Angular 6 wildcard route for handling 404 errors, I encountered an issue when trying to serve the application with nginx. Despite building the app into index.html and static fi ...

Upon updating from Angular5 to Angular7, the slice pipe seems to be stuck in an endless loop

Recently, I upgraded my project from angular 5 to angular 7. However, after completing the upgrade, I noticed that the slice pipe was not functioning correctly. It seemed to be causing infinite loops in the angular core files and even resulted in my browse ...