Tips for passing an array between components in Angular 2

My goal is to create a to-do list with multiple components. Initially, I have 2 components and plan to add more later. I will be sharing an array of tasks using the Tache class.

Navbar Component

import { Component } from '@angular/core';
import { Router } from '@angular/router';

import { Tache } from './tache';
import { TacheService } from './tache.service';
import { InMemoryDataService } from './en-memoire';
@Component({
  selector: 'navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.css']
})
export class NavBarComponent {
  constructor(
    private tacheService: TacheService) {}

  add(name: string): void {
    name = name.trim();
    if (!name) {return;}
    this.tacheService.create(name)
      .then(tache => {
        return insert(tache);
      });
  }
}

TachesInit Component

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { Tache } from './tache';
import { TacheService } from './tache.service';
import { InMemoryDataService } from './en-memoire';

@Component({
  selector: 'tachesInit',
  templateUrl: './tachesInit.component.html',
  styleUrls: ['./tachesInit.component.css']
})
export class TachesInitComponent implements OnInit {

  tacheSelectionnee: Tache;
  constructor(
    private tacheService: TacheService) {}
  ngOnInit(): void {
    this.tacheService.getTaches()
      .then(taches => this.taches = taches);
  }
}

Service

import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';

import 'rxjs/add/operator/toPromise';

import { Tache } from './tache';

@Injectable()
export class TacheService {
  private headers = new Headers({'Content-Type': 'application/json'});
  private tachesUrl = 'api/taches';  // URL to web api
  taches: Tache[] = [];

  tacheSelectionnee: Tache;

  constructor(private http: Http) {}
  getTaches(): Promise<Tache[]> {
    return this.http.get(this.tachesUrl)
      .toPromise()
      .then(response => {
        let taches = response.json().data as Tache[];
        console.log(taches);
        return taches;
      })
      .catch(this.handleError);
  }

  create(name: string): Promise<Tache> {
    return this.http
      .post(this.tachesUrl, JSON.stringify({name: name, stat: 0}), {headers: this.headers})
      .toPromise()
      .then(res => res.json().data as Tache)
      .catch(this.handleError);
  }

  insert(tache: Tache): void {
    this.taches.push(tache);
  }
}

The TachesInit Component is not yet finished, and I intend to use the function insert in both components to pass and save data in the taches array declared in the service so that all components can access the same data. However, I am encountering an error:

src/app/navbar.component.ts(26,15): error TS2304: Cannot find name 'insert'

PS: Any alternative solutions or suggestions are welcome.

Answer №1

Ensure that on line 26, you are executing the following action:

this.tacheService.insert(name)

If all of your components require access to the same Tache[] array, consider implementing a clean solution by retrieving this value directly from the service when necessary. Instead of maintaining taches as an instance variable within each component:

taches: Tache[] = [];

You should place this instance variable in the service instead. Subsequently, either access this variable directly from the service (satisfactory but not ideal) or create a function within the service to retrieve it (preferred).

An alternative approach, if storing the Tache[] in components is unavoidable, would be for the tache service to expose a Tache[] subscription and have all components subscribe to it. For more information, refer to this resource.

Answer №2

It is required that the component remains stateless, with all state data being managed by the service.

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

issue with useReducer not functioning as expected

I encountered an issue with my customized Select component. It includes a select and options while listening for onChange events. Additionally, I am using a useReducer function that initializes some variables. However, even after selecting an option, the s ...

There will be no pop-up notification displayed if the product is already in the cart

When a product is added to the cart, the following code is used: addproduct(itemId) { this.showLoading = true this.$http.post('/shampoo', {'item': itemId}).then((response) => { swal({ title: "Success!", ...

Having difficulty executing the command 'npm install -g expo-cli'

When attempting to execute npm install - g expo-cli on a Windows 10 machine, I am encountering issues. An error message keeps popping up and preventing me from proceeding. I'm in desperate need of assistance! npm WARN deprecated <a href="/cdn-cgi/ ...

"Failed to insert or update a child record in the database due to a SQL

I encountered an issue while trying to perform the following transaction: static async save(habit){ await db.beginTransaction; try { await db.execute('SELECT @habitId:=MAX(habits.habitId)+1 FROM habits'); await db.execute( ...

Tips on switching the default camera with ngx-scanner-qrcode library in Angular

In my current project, I am utilizing the ngx-sanner-qrcode library for QRCode scanning. However, I am interested in changing the default camera from front to back in order to enhance the user experience. I assumed that I could change the default camera b ...

Sources of the TypeScript library in WebStorm

I'm brand new to TypeScript. I decided to use WebStorm because I'm familiar with JetBrains tools. In other programming languages, I'm used to having a workflow that includes some kind of dependency management system like Maven, which allows ...

Cannot locate module using absolute paths in React Native with Typescript

I recently initiated a new project and am currently in the process of setting up an absolute path by referencing this informative article: https://medium.com/geekculture/making-life-easier-with-... Despite closely following the steps outlined, I'm en ...

Issue with Firefox causing problems with smooth scrolling Javascript on internal links

I recently created a one-page website using Bootstrap. The navigation menu items are internal links that point to different sections within the page, and I added some smooth scroll JavaScript for a more polished scrolling effect. While the website functio ...

Various hues blending and intertwining with one another

https://i.stack.imgur.com/zLrNK.png Could someone please clarify what is happening here? I'm attempting to change the background color to dodgerblue, but for some reason, the white background color is still showing through. Below is the code snippet ...

Utilizing jQuery to dynamically pass parameters to the YouTube API

When making a request to the YouTube API, I am structuring it as follows: $.get("https://www.googleapis.com/youtube/v3/channels", { part: "contentDetails", id: "somestring", key: "MY-API-KEY" } /*, ...*/ ) A hidden field contains the value id ...

Attempting to transfer a string variable into a JavaScript scope within an HTML document using handlebars-express

Struggling to pass a variable from server-side to client-side using handlebars-express... After searching through the content here for some time, I realize I might need some help. I've confirmed that the object passed is indeed of string type, but h ...

Utilizing Supabase queries alongside React's Hot Toast Promise: A Comprehensive Guide

I'm currently working on an admin panel to manage my website. As part of the development, I am using Supabase for the Database and React Hot Toast for notifications. Recently, I attempted to implement Toast Promise using the following code: const add ...

Automatically assign the creation date and modification date to an entity in jhipster

I am currently working on automatically setting the creation date and date of the last change for an entity in JHipster, utilizing a MySQL Database. Below is my Java code snippet for the entity: @GeneratedValue(strategy = GenerationType.AUTO) @Column(nam ...

Experiencing migraines while integrating Firebase 9, Redux Toolkit, and Typescript in a React project. Encountering a peculiar issue where 'dispatch' is unexpectedly identified as type 'never'?

I am currently in the process of upgrading an old project to newer technologies, specifically focusing on Typescript, redux-toolkit, and Firebase v9 for modularity. While I have limited experience with Typescript and none with redux-toolkit, I have been us ...

Setting maximum and minimum zoom limits for an element ID using JavaScript or jQuery

My application features a DIV element with the unique identifier of mainDiv. The issue I am facing is related to zooming functionality, as it currently lacks any set limits - both for scaling up and scaling down. I have been searching on Google for a sol ...

It appears that Stackblitz may have an outdated package.json file for older Angular projects, causing compatibility issues when running the project locally

Upon reviewing the package.json files for older Angular projects on Stackblitz, I have observed a pattern where Angular9 is listed under devDependencies while dependencies include older versions such as "@angular/core": "7.2.2" or "@angular/core": "6.1.10" ...

Error: Unable to locate module 'react-calendar-heatmap'

After successfully creating a component that functioned flawlessly in my local application, I encountered an error when attempting to integrate it with npm: ./src/App.js Module not found: Can't resolve 'heatmap-calendar-react' in 'C:& ...

When I upload a file using v-file-input, it displays two names

While working with nuxt, I made an interesting discovery. See the pattern here The top name is the file that was uploaded, and the bottom one is the target file name. I plan to remove the bottom name and replace it with the top. This is what I envision: E ...

Can Angular's built-in internationalization features be used to translate bindings?

Challenge The task at hand involves integrating translations into an Angular 6 application to support static text in multiple languages. The objective is to have the ability to choose a language during the build process without requiring dynamic translati ...

What is the approach of Angular 2 in managing attributes formatted in camelCase?

Recently, I've been dedicating my time to a personal project centered around web components. In this endeavor, I have been exploring the development of my own data binding library. Progress has been made in creating key functionalities akin to those f ...