Angular2가 있는 서비스에서 구성 요소의 변수 변경 업데이트
내 앱에는 이름을 저장하는 네임 서비스가 있습니다.
앱에는 이 서비스를 참조하는 Navbar와 The Content라는 두 가지 하위 구성 요소가 있습니다.서비스에서 이름이 변경될 때마다 다른 두 구성 요소에서 모두 업데이트하기를 원합니다.어떻게 해야 하나요?
import {Component, Injectable} from 'angular2/core'
// Name Service
@Injectable()
class NameService {
name: any;
constructor() {
this.name = "Jack";
}
change(){
this.name = "Jane";
}
}
// The navbar
@Component({
selector: 'navbar',
template: '<div>This is the navbar, user name is {{name}}.</div>'
})
export class Navbar {
name: any;
constructor(nameService: NameService) {
this.name = nameService.name;
}
}
// The content area
@Component({
selector: 'thecontent',
template: '<div>This is the content area. Hello user {{name}}. <button (click)=changeMyName()>Change the name</button></div>'
})
export class TheContent {
name: any;
constructor(public nameService: NameService) {
this.name = nameService.name;
}
changeMyName() {
this.nameService.change();
console.log(this.nameService.name);
}
}
@Component({
selector: 'app',
providers: [NameService],
directives: [TheContent, Navbar],
template: '<navbar></navbar><thecontent></thecontent>'
})
export class App {
constructor(public nameService: NameService) {
}
}
서비스에서 이벤트를 제공하고 구성 요소에서 이벤트를 구독합니다.
@Injectable()
class NameService {
name: any;
// EventEmitter should not be used this way - only for `@Output()`s
//nameChange: EventEmitter<string> = new EventEmitter<string>();
nameChange: Subject<string> = new Subject<string>();
constructor() {
this.name = "Jack";
}
change(){
this.name = 'Jane';
this.nameChange.next(this.name);
}
}
export class SomeComponent {
constructor(private nameService: NameService) {
this.name = nameService.name;
this._subscription = nameService.nameChange.subscribe((value) => {
this.name = value;
});
}
ngOnDestroy() {
//prevent memory leak when component destroyed
this._subscription.unsubscribe();
}
}
참고 항목
angular.io - COMPINE Interaction - 부모와 자식이 서비스를 통해 통신합니다.
부터name
에NameService
원시 유형이므로 서비스 및 구성 요소에서 다른 인스턴스를 얻을 수 있습니다.변경할 때name
에NameService
구성 요소 속성에 여전히 초기 값이 있고 바인딩이 예상대로 작동하지 않습니다.
여기에 각 1 "점 규칙"을 적용하고 참조 유형에 바인딩해야 합니다.바꾸다NameService
이름을 포함하는 개체를 저장합니다.
export interface Info {
name:string;
}
@Injectable()
class NameService {
info: Info = { name : "Jack" };
change(){
this.info.name = "Jane";
}
}
이 개체에 바인딩하고 에 대한 업데이트를 가져올 수 있습니다.name
자동으로 속성을 지정합니다.
// The navbar
@Component({
selector: 'navbar',
template: '<div>This is the navbar, user name is {{info.name}}.</div>'
})
export class Navbar {
info: Info;
constructor(nameService: NameService) {
this.info = nameService.info;
}
}
저는 귄터가 제공하는 해결책이 가장 좋다고 생각합니다.
즉, Angular2 서비스는 인젝터 트리에서 발생하는 싱글톤이라는 것을 알아야 합니다.이는 다음을 의미합니다.
- 애플리케이션 레벨에서 서비스를 정의하는 경우(의 두 번째 매개 변수 내)
bootstrap
method), 인스턴스는 모든 요소(구성 요소 및 서비스)에서 공유할 수 있습니다. - 구성요소 수준에서 서비스를 정의하는 경우(내)
providers
속성), 인스턴스는 구성 요소 및 해당 하위 구성 요소에 한정됩니다.
이러한 측면에 대한 자세한 내용은 "계층적 종속성 주입" 문서를 참조하십시오. https://angular.io/docs/ts/latest/guide/hierarchical-dependency-injection.html
도움이 되길 바래, 티에리
언급URL : https://stackoverflow.com/questions/34714462/updating-variable-changes-in-components-from-a-service-with-angular2
'programing' 카테고리의 다른 글
범위 검색 대 고유 검색 대 건너뛰기 검색 (0) | 2023.08.07 |
---|---|
MYSQL - 날짜/초 (0) | 2023.08.07 |
입력 내부의 텍스트를 정렬하는 방법은 무엇입니까? (0) | 2023.08.07 |
HTMLU가 Javascript를 기다리지 않음 (0) | 2023.08.07 |
이미지에서 도커 파일을 생성하는 방법은 무엇입니까? (0) | 2023.08.07 |