"Encountering an issue when trying to append an array of objects into a new

As I attempt to display my data (specifically recipes) on the frontend, I encounter an issue. When I log the data received from the server, I notice that it is an object with a 'msg' property containing an array of objects. To access this array, I can use data['msg' as keyof typeof data]. By doing so, I obtain an array of objects. However, when I try to assign this array to the this.recipe array using

this.recipe = data['msg' as keyof typeof data]
, I encounter an error:

Type 'Function' is missing the following properties from type 'Recipe[]': pop, push, concat, join, and 27 more.

Furthermore, attempting to use push() results in:

Type 'Function' is missing the following properties from type 'Recipe': description, ingredients

Being relatively new to Angular, I'm feeling lost and unsure how to resolve this issue. If additional code snippets would be helpful, please let me know. For now, I've included the file where the problem arises.

The problematic code snippet is shown below:

export class ListComponent implements OnInit {
  public recipes: Recipe[];
  constructor(private _recipeService: RecipeService) { }

  ngOnInit(): void {
    this.readRecipes();
  }
  readRecipes() {
    this._recipeService.readRecipes().subscribe({
      next: (data) => {
        this.recipes = data['msg' as keyof typeof data];
      }
      ,
      error: (error) => console.log(error),
      complete: () => console.info('complete')

    }

    )
  }

}

Code for my recipe.service.ts file:

export class RecipeService {
  private baseUri: string = "http://localhost:8080";
  private headers = new HttpHeaders().set('Content-Type', 'application/json')
  constructor(private http: HttpClient) { }


  createRecipe(recipe: Recipe) {
    return this.http.post(this.baseUri + '/create', recipe, { headers: this.headers });
  }

  readRecipes() {
    return this.http.get(this.baseUri + '/read', { headers: this.headers });
  }

  updateRecipe(recipe: Recipe) {
    return this.http.put(this.baseUri + '/update', recipe, { headers: this.headers });
  }

  deleteRecipe(id: string) {
    return this.http.delete(this.baseUri + '/delete/' + id, { headers: this.headers });
  }
}

Backend portion of code for the read route:

router.get('/read', (req, res, next) => {
Recipe.find({}, (err, recipes) => {
    if (err)
        res.status(500).json({
            errmsg: err
        });
    res.status(200).json({
        msg: recipes
    });

});
});

Answer №1

An easier alternative to achieve this task is by utilizing the async pipe within Angular:

@Component({
  template: `
    <ul *ngIf="(employees$ | async).length">
      <li *ngFor="let employee of employees$ | async">{{employee.name}}</li>
    </ul>  
  `
})
export class EmployeesComponent implements OnInit { 
  employees$: Observable<Employee[]>;
 
  constructor(private service: MyService) {}
 
  ngOnInit() {
    this.employees$ = this.service.getEmployees$();
  }
}

To see a demonstration of the recipe list, you can view this modified version on Stackblitz: https://stackblitz.com/edit/angular-ivy-r97jph?file=src/app/components/list/list.component.ts

Answer №2

I just wanted to share that I was able to find a solution.

Initially, I was sending the response from the backend as res.JSON({msg:recipes}), but I couldn't access the msg object. However, after changing the code to res.JSON(recipes) with only parentheses (), I successfully retrieved the array. Subsequently, by creating a new variable called data, I was able to access the response array using this.recipes=data.

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

Tips on leveraging separate files for classes in TypeScript

I'm currently working on developing a TypeScript application where each class is saved in its own .ts file. I prefer to use VS Code for this project. So far, my compile task seems to be functioning correctly (transpiling .ts files into .js files). How ...

Encountering a JSON error in Ionic 3 due to a circular structure conversion

Hello everyone, I am a beginner in Angular 2+ and Ionic 3. I am currently attempting to submit a login form from my Ionic 3 app to my ASP.NET Web API application for token-based authentication. However, I keep encountering the following error: converting c ...

Encountered an error while trying to upgrade Angular from version 9 to 10: The package '-e' is not recognized as a dependency

Anyone else run into this problem while upgrading an Angular app from version 9 to 10? The error message reads: ng update @angular/core@10 @angular/cli@10 I tried searching online but couldn't find any solutions that addressed my specific issue. ...

Is it possible to modify the dropdown menu so that it opens on the right side instead of using a select tag?

Is there a way to make the drop-down from the select tag open to the right side(drop-right)? <label for="ExpLabel">Select Message Expiry:</label> <select name="ExpSelect" id="Expiry"> <option value="ExpiryDate">1 Day</opt ...

Converting enum flags to strings

I'm encountering an issue with converting enum flags to strings and parsing them. Here is an example of my enum: enum CookieOptions { None = 0, Necessary = 1 << 0, Analytical = 1 << 1, Marketing = 1 << 2, Personalization = ...

Displaying HTML content in Angular 15

Struggling with Angular 15.2, I'm attempting to develop a component that can render valid HTML input. My initial approach involved using ElementRef and innerHTML: constructor( private readonly componentElement: ElementRef, ) {} ngOnInit(): void { ...

The Ionic serve command fails to recognize and reflect any saved changes, leading to a lack of automatic reloading

Recently, I encountered a strange issue while using my ionic 2 application. Whenever I execute the ionic serve command, it launches the server on localhost and produces the following output: [12:00:45] ionic-app-scripts 0.0.45 [12:00:46] watch started ...

I'm experiencing an issue with my website where it appears broken when I build it, but functions properly when I use npm run dev in Next

For my project, I have utilized NextJs, Tailwind, React, and Typescript. It is all set and ready to be hosted. After using "output: export" in next.config.js and running npm run build, the process was successful. However, when viewing my website locally, I ...

Leveraging Global Variables in TypeScript with Node Express

Having issues using global variables in node express when working with typescript. Specifically, trying to use the same global array variable tokenList:tokList across multiple modules and middleware, but haven't been successful so far. Any suggestions ...

Access values of keys in an array of objects using TypeScript during array initialization

In my TypeScript code, I am initializing an array of objects. I need to retrieve the id parameter of a specific object that I am initializing. vacancies: Array<Vacancy> = [{ id: 1, is_fav: this.favouritesService.favourites.find(fav = ...

The TypeScript elusive bug is making me lose my mind: Struggling to exclude types using control statements

I encountered a recurring error that I managed to narrow down to a specific scenario which only occasionally replicates on the TypeScript Playground, but consistently fails when running tsc locally. type Result = { success: true, value: string, } | { ...

Using TypeScript along with Nuxt.js and Vuex to access methods from an imported class

Currently, I am in the process of developing a nuxt.js application with typescript and my goal is to segregate the API Calls from the vuex store. However, I've encountered an issue where it seems like I cannot utilize the methods when importing the cl ...

Is it possible to detect changes in the p-columnFilter match options and trigger a function in Angular and PrimeNG?

Is there a way to attach a function that triggers every time the user selects an option from the matchOption of p-columnFilter. <p-columnFilter type="date"> ... </p-columnFilter> https://i.sstatic.net/LHPa4.png For example, you can ...

Filtering data in an antd table by searching

Just starting out with React hooks, specifically using TypeScript, and I'm struggling to implement a search filter with two parameters. Currently, the search filter is only working with one parameter which is 'receiver?.name?'. However, I wo ...

How can you rearrange the order of objects in an array to only include duplicates?

https://i.sstatic.net/XwCDZ.png I don't want to alter the original order of objects in an array. However, I do need to retrieve items in a specific sequence when both the location and place are identical. I attempted a solution but it requires an ad ...

Error message: Invariant Violation: Portal.render() being caused by semantic-ui-react Basic Modal

As part of enhancing an existing React component, I attempted to include a basic modal (link to documentation). Everything was working well without the modal, but once I added it in following the semantic-ui-react guidelines, I encountered a runtime error ...

Angular Reactive Forms: Implementing Error Display and Red Border Styling

Recently, I've started diving into Angular Reactive Forms and I'm quite impressed by the async validator feature for tasks that involve checking data against a database. The separation of validation rules from the GUI is also very appealing to me ...

Incorporating HttpClient in the ngOnInit method of Angular allows for the seamless retrieval of JSON data and its conversion into

Whenever I initialize the HttpClient(this.http) to retrieve data in the ngOnInit() method: ngOnInit(): void { this.http.get('http://127.0.0.1:3000/getData').subscribe((data) => { const type = this.route.snapshot.paramMap.get(' ...

Angular encountered an issue while attempting to access the property 'results' of an undefined value

I've got the code functioning perfectly, but for some reason I'm not getting any errors in the console log. It seems like I can't access results from an indefinite property. Any ideas on what could be causing this issue? I'm trying to m ...

Angular Signal computation does not initiate a re-render

I am currently working on sorting an array of signals within my component. To achieve this, I have wrapped the array in a compute function that sorts it. Below is the relevant code snippet: In the Service file: private readonly _lobbies = signal<Lobby ...