할 일 목록을 만들고 싶습니다. 2 개의 구성 요소가 있습니다 (나중에 더 많음) Tache
.
Navbar 구성 요소
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 구성 요소
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);
}
}
서비스
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);
}
}
TachesInit 구성 요소가 완료되지 않은 상태 insert
에서 두 함수 를 사용하여 데이터를 전달 taches
하고 서비스에서 선언 된 배열에 저장합니다 (모든 구성 요소가 데이터에 액세스 할 수 있도록) 오류가 발생합니다.
src/app/navbar.component.ts(26,15): error TS2304: Cannot find name 'insert'
추신 : 더 쉬울 경우 다른 솔루션을 수락합니다.
26 행에서 다음을 수행해야합니다.
this.tacheService.insert(name)
모든 구성 요소가 동일한 Tache []에 액세스해야합니까? 이 경우이를 구현하는 가장 깨끗한 방법은 필요할 때 서비스에서 직접 해당 값을 가져 오는 것입니다. 따라서 구성 요소의 인스턴스 변수로 태 치를 저장하는 대신 :
taches: Tache[] = [];
대신 해당 인스턴스 변수를 서비스에 넣으십시오. 그런 다음 서비스에서 해당 변수에 직접 액세스하거나 (eh) 서비스에서이를 반환하는 함수를 구현합니다 (더 나은).
어떤 이유로 구성 요소에 Tache []를 절대적으로 저장해야하는 또 다른 옵션은 tache 서비스가 Tache [] 구독을 노출하고 모든 구성 요소가 구독하도록하는 것입니다. http://blog.angular-university.io/how-to-build-angular2-apps-using-rxjs-observable-data-services-pitfalls-to-avoid/를 참조하세요 .
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다