Attempting to retrieve information from the database using Angular 6

Hello, I am currently attempting to retrieve data from a database and display it in a table. Below is the code for the service I have created:

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Subject } from "rxjs";
import { map } from 'rxjs/operators';

import { Post } from "./post.model";

@Injectable({ providedIn: "root" })
export class PostsService {
  private posts: Post[] = [];
  private postsUpdated = new Subject<Post[]>();

  constructor(private http: HttpClient) {}

  getPosts() {
    this.http
      .get<{ message: string; posts: any }>(
        "http://localhost:3000/api/posts"
      )
      .pipe(map((postData) => {
        return postData.posts.map(post => {
          return {
            title: post.title,
            content: post.content,
            id: post._id
          };
        });
      }))
      .subscribe(transformedPosts => {
        this.posts = transformedPosts;
        this.postsUpdated.next([...this.posts]);
      });
  }

  getPostUpdateListener() {
    return this.postsUpdated.asObservable();
  }

  addPost(title: string, content: string) {
    const post: Post = { id: null, title: title, content: content };
    this.http
      .post<{ message: string, postId: string }>("http://localhost:3000/api/posts", post)
      .subscribe(responseData => {
        const id = responseData.postId;
        post.id = id;
        this.posts.push(post);
        this.postsUpdated.next([...this.posts]);
      });
  }

  deletePost(postId: string) {
    this.http.delete("http://localhost:3000/api/posts/" + postId)
      .subscribe(() => {
        const updatedPosts = this.posts.filter(post => post.id !== postId);
        this.posts = updatedPosts;
        this.postsUpdated.next([...this.posts]);
      });
  }
}

Upon running the code, two different errors are encountered:

When using Mozilla Firefox, the error received is:

ERROR TypeError: "_this.posts is undefined"

While using Google Chrome, the error displayed is:

core.js:1542 ERROR TypeError: Cannot read property 'slice' of undefined at SafeSubscriber._next (posts.service.ts:39)

If anyone has insights or suggestions on why these errors occur, please feel free to share. Thank you.

Answer №1

Ensure that the value of this.posts is not null when calling

this.updatedPosts.next([...this.posts])
. To prevent any runtime errors, consider using
this.updatedPosts.next(this.posts)
as an alternative if this.posts is null

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

Setting compilerOptions.paths is not allowed as alias imports are not supported

Seeking a solution to escape the chaos of relative paths in my React App based on Create-React-App. After referencing this helpful Stack Overflow thread, I updated my tsconfig.json file as follows: { "compilerOptions": { "baseUrl" ...

The system encountered a TypeError: Unable to access the 'nativeElement' property as it is undefined

Hello, I am a beginner in Angular 2 and currently working on an image cropping plugin. My goal is to display the image on a canvas element. Below is my HTML code: <div class="row"> <div class="col-sm-6"> <canvas id="layout" width="40 ...

How can you store form field validation rules (for example, firstname.dirty) in an array within TypeScript in Angular?

How do I save form field validation rules in an array? What should replace /'''''HERE'''''/ with? formfields: Array<Object> = [ {label: "Employer:", control: "employer", val ...

Invoking a parent method from a child component in a TypeScript and React application

I'm facing an issue where I am unable to call a method from a parent component in my child component. The method in the parent element is not being triggered when the child component tries to call it. This problem is showcased in a simple example with ...

When working with Angular in VSCode and using PHP, an error message may appear stating that "php" is not recognized as a cmdlet, function, script file, or operable program

I've been attempting to execute my PHP file in VSCode, but even after adding the path to the environment variables, I keep encountering the following error: `php : The term 'php' is not recognized as the name of a cmdlet, function, scr ...

Unable to perform live reload in vscode Development Container when working with Angular

I recently tackled a mock application project in Angular using the VScode Development Container. To set it up, I created a Docker instance and generated the devcontainer.json file by utilizing the "Add Development container configuration file" feature. Mo ...

Error in Typescript: The type 'string' cannot be assigned to the type '"allName" | `allName.${number}.nestedArray`' within the react hook form

Currently, I am tackling the react hook form with typescript and facing a challenge with my data structure which involves arrays within an array. To address this, I decided to implement the useFieldArray functionality. allName: [ { name: "us ...

What could be causing React to generate an error when attempting to utilize my custom hook to retrieve data from Firebase using context?

Currently, I am restructuring my code to improve organization by moving data fetching to custom hooks instead of within the component file. However, I am encountering issues with the hook not functioning properly when used in conjunction with my context. ...

Launching npm using the command "npm run protractor" results in console errors being thrown upon completing the test

Recently, we made the decision to streamline the installation process of Protractor on local machines by specifying it in package.json rather than installing it individually with the -g flag. The addition we made looks something like this: "scripts": { ...

Guide to setting up .env Variables on a DigitalOcean Ubuntu droplet

After deploying my Node.js app on a DigitalOcean Ubuntu droplet, I encountered the need for variables from my .env file. How can I go about creating these variables within the DigitalOcean droplet? ...

Change the color of active buttons on dynamically generated buttons

My current challenge involves getting a button to stay active when pressed, especially when dealing with dynamically created buttons. Here is my current setup: <Grid container sx={{ padding: "10px" }}> {Object.values(CATEGORIES).map((c) => { ...

Exporting modules in TypeScript using "module.exports"

While working on my Yeoman generator, I initially wrote it in JavaScript like this: "use strict"; var Generator = require("yeoman-generator"); var chalk = rquire("chalk"); module.exports = class extends Generator { initializing() { this.log( c ...

Ionic 2 - renders an array of objects [object, object]

The following code snippet shows how I use array push: let results = this.allExercises[i]; this.dataArray.push(results); To pass data with navParams and navigate to a new page, I do the following: this.navCtrl.push(HomePage, { 'exercisesDone&ap ...

NgClass does not support mdi-timelapse icons

Here's the code snippet that I am working with: <i class="mdi" [ngClass]="{ 'not-started mdi-timer': task.state === 'NOT_STARTED', 'started mdi-timelapse': task.state === 'STARTED', ...

What steps should I take to avoid harmful automatic approvals during application launch while utilizing the "angular-auth-oidc-client"?

Utilizing the "angular-auth-oidc-client" in my app is crucial, operating in mode "silent_run": true. The app initiates with various routes, always accompanied by query parameters. Majority of the resources within the application do not necessitate server a ...

Webpack integration for Angular 2 localization

I'm currently trying to implement internationalization in Angular using Webpack instead of SystemJS, following the Angular cookbook guidelines found here. However, the cookbook provides a snippet that relies on SystemJS for loading translation files: ...

Can the SharePoint Graph API be accessed in Angular without requiring Azure app registration delegates and application permissions?

After creating our Angular application, we successfully implemented single sign-on using Azure app registration and MSAL library. Our goal is to access the SharePoint document graph API without requiring delegate or application level permissions in the ap ...

Angular-cli does not come with the Bootstrap framework pre-installed

After installing the bootstrap framework to my angular2 project through npm, I noticed that it appeared in the node-modules folder. However, upon checking the angular-cli file, I discovered that the boostrap script and css were not included. "apps": [ ...

How can angular/typescript be used to convert a percentage value, such as 75.8%, into a number like 75.8?

I have obtained a value (for example, "75.8%") as a string from an API and I need to convert it to a number in order to apply conditions. For instance: <div class="container" [ngClass]="{ 'pos' : value > 0, ...

A guide on validating an array of literals by leveraging the power of class-validator and class-transformer through the methods plainToInstance or plainTo

I am struggling with my validation not working properly when I use plainToInstance to convert literals to classes. Although the transformation appears to be successful since I get Array(3) [Foo, Foo, Foo] after using plainToInstance(), the validation does ...