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.