Measuring Feedback: Utilizing Angular 4 to calculate review ratings

I'm facing a challenge while working on a review form using Firebase and Angular 4. The issue is with calculating the total length of added reviews and the sum of their ratings. Each time a new review is submitted, it gets pushed to a list of objects representing recently added reviews. I am struggling to iterate over these reviews and calculate the average rating by dividing the total sum by the number of reviews.

https://i.sstatic.net/0Z1u0.png

review.component.ts

export class ProductReviewsComponent implements OnInit {
  @Input("product") product: Product;
  currentRate = 8;
  review = {};
  reviews = {};
  description;
  product$;
  number = [];

  constructor(private reviewService: ReviewsService) {}

  async ngOnInit() {
    this.product$ = await this.reviewService.getReview(this.product.$key);
    this.number = [];
    console.log(this.number);
  }

  addReview() {
    let review = {
        rate: this.currentRate,
        description: this.review
    }

    this.reviewService.saveReview(this.product.$key, review);
  }
}

html

<form #f="ngForm">
  <div class="form-group">
    <ngb-rating [(rate)]="currentRate"></ngb-rating>
    <textarea #description="ngModel" [(ngModel)]="review.description" name="description" type="text" class="form-control" placeholder="Dodaj opis..."
      required></textarea>
    <div class="alert alert-danger" *ngIf="description.touched && description.invalid">
      <div *ngIf="description.errors.required">Name is required</div>
    </div>

  </div>

  <button (click)="addReview()" class="btn btn-primary">Dodaj opinię</button>

  <div *ngFor="let review of product$ | async">
    {{ review.rate }} {{ review.description.description }}
  </div>


</form>

Answer №1

firebase.database.DataSnapshot forEach

If you take a closer look, it appears that you can easily loop through the response snapshot and add the key:value pairs to an array (only if the key matches your desired key). After that, using .then, you will have the length of your array along with the data for further processing.

// Assuming we have the following data in our Database:
{
  "users": {
    "ada": {
      "first": "Ada",
      "last": "Lovelace"
    },
    "alan": {
      "first": "Alan",
      "last": "Turing"
    }
  }
}

// Iterate through users sequentially using the forEach() method. The callback
// provided to forEach() will be executed synchronously for each child DataSnapshot:
var query = firebase.database().ref("users").orderByKey();
query.once("value")
  .then(function(snapshot) {
    snapshot.forEach(function(childSnapshot) {
      // The variable 'key' will represent "ada" on the first iteration and "alan" on the second
      var key = childSnapshot.key;
      // The variable 'childData' will contain the actual content of the child
      var childData = childSnapshot.val();
  });
});

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

Struggling with Angular 8: Attempting to utilize form data for string formatting in a service, but encountering persistent page reloading and failure to reassign variables from form values

My goal is to extract the zip code from a form, create a URL based on that zip code, make an API call using that URL, and then display the JSON data on the screen. I have successfully generated the URL and retrieved the necessary data. However, I am strug ...

Attempting to invoke a TypeScript firebase function

I'm currently working on incorporating Firebase functions in my index.ts file: import * as functions from "firebase-functions"; export const helloWorld = functions.https.onRequest((request, response) => { functions.logger.info(" ...

The following error was encountered while building Angular 2 with Webpack at src/app/userManagement/unlockUserID/unlockUserID.component.ts, on line 7

Ever since I set up my routing, I've been encountering a persistent error message: ERROR in [at-loader] src/app/userManagement/unlockUserID/unlockUserID.component.ts:7:5 I'm utilizing angular-cli and below is an excerpt from my package.json: d ...

Best practices and distinctions when it comes to typing in TypeScript functions

Do the typings below differ in any way, or are they essentially the same with personal preference? interface ThingA{ myFunc(): number; } interface ThingB{ myFunc: () => number; } ...

Adding a fresh element to an object array in TypeScript

How can we add a specific value to an array of objects using TypeScript? I am looking to insert the value 1993 into each "annualRentCurrent" property in the sample object. Any suggestions on how to achieve this in TypeScript or Angular? Thank you! #Data ...

Create allowances for specific areas

One of my methods involves the saving of an author using the .findOneAndUpdate function. The structure of AuthorInterface is as follows: export interface AuthorInterface { name: string, bio: string, githubLink: string, ...

"What is the best way to apply multiple filters to an array in a React

Is there a way to incorporate dropdown menus along with search text input for filtering an array in React? I would like to give users the option to select a location and then search for specific results within that location. Any suggestions on how to ach ...

I need assistance with adding a button to a table cell that triggers an action when clicked

I need to add a button to the table cell when I click a button to insert a new row in an Angular table. Although I am successful in adding a new row, I am facing difficulty in including a button in the cell along with the newly created row. ...

Troubleshooting Angular and ASP.NET Core MVC: Addressing the "Uncaught SyntaxError: Unexpected token '<'" issue with index file references post deployment

My application is built using ASP.NET Core MVC and an Angular UI framework. Everything runs smoothly in the IIS Express Development Environment, but when switching to the IIS Express Production environment or deploying to an IIS host, I encounter issues wi ...

Accessing an external API through a tRPC endpoint (tRPC Promise is resolved before processing is complete)

I want to utilize OpenAI's API within my Next.js + tRPC application. It appears that my front-end is proceeding without waiting for the back-end to finish the API request, resulting in an error due to the response still being undefined. Below is my e ...

Retrieving the key from an object using an indexed signature in Typescript

I have a TypeScript module where I am importing a specific type and function: type Attributes = { [key: string]: number; }; function Fn<KeysOfAttributes extends string>(opts: { attributes: Attributes }): any { // ... } Unfortunately, I am unab ...

What is the best way to update properties in a child component using React hooks?

Looking to update the props using react hooks, I came across a method of passing setState function as props to the child component. MainContainer.tsx const MainContainer: React.FC = () => { const [count, setCount] = useState(0); return <Counter ...

The Angular Reactive Forms error message indicates that attempting to assign a 'string' type to an 'AbstractControl' parameter is invalid

While attempting to add a string value to a formArray using material forms, I encountered the following error message: 'Argument of type 'string' is not assignable to parameter of type 'AbstractControl'.' If I try adding a ...

How can I add a parameter to a JSON URL in Angular?

I'm looking to enhance my URL by adding a new parameter, but I'm unsure of the steps needed. ts.file route(name:string) { this.router.navigate(['/homepage', (name)]); console.log('name); } service private url1 = './assets/ ...

I am experiencing difficulties with implementing Angular material components in my project

I recently encountered an issue while trying to integrate angular material into my project. Despite importing the MatFormFieldModule, I received the following error: ERROR in src/app/login/components/login/login.component.html:2:1 - error NG8001: &apo ...

Angular 8 combined with Mmenu light JS

Looking for guidance on integrating the Mmenu light JS plugin into an Angular 8 project. Wondering where to incorporate the 'mmenu-light.js' code. Any insights or advice would be greatly appreciated. Thank you! ...

Exploring nested JSON responses in Angular 2 with TypeScript

Below is the JSON response I received from the REST endpoint: {"image_2_11_0-51-upgrade.iso": {"model": "somemodel", "hostnames": ["abc.com", "abcd,com"], "upload_status": false, "version": "2.11.0-51"}, "image_2_11_0-51-upgrade.iso": {"model": "newmo ...

The Angular2 cli throws an error stating: "Cannot add a new entry to an existing one."

I have been utilizing the Angular2 Cli as my runtime environment for my Angular 2 application and I must say, I am thoroughly impressed by its architecture, top-notch development tools, and overall well-thought-out design. However, every so often, specifi ...

Can you provide the syntax for a generic type parameter placed in front of a function type declaration?

While reviewing a project code recently, I came across some declarations in TypeScript that were unfamiliar to me: export interface SomeInterface<T> { <R>(paths: string[]): Observable<R>; <R>(Fn: (state: T) => R): Observable ...

Tips on implementing zod schema types with remapped fields using the toZod method

I'm currently working on mapping a schema key to a different name in my database interface Country { isoCode: string, nameEn: string, nameDe: string, phone: string, bla: string } const CountryJson = { i ...