gpt4 book ai didi

javascript - 使用 angular2 从服务更新组件中的变量更改

转载 作者:IT王子 更新时间:2023-10-29 02:50:31 29 4
gpt4 key购买 nike

我的应用程序有一个保存名称的名称服务。

App 有两个子组件,Navbar 和 TheContent 引用了此服务。每当服务中的名称发生变化时,我都希望它在其他两个组件中都进行更新。我该怎么做?

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 - COMPONENT INTERACTION - Parent and children communicate via a service

关于javascript - 使用 angular2 从服务更新组件中的变量更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34714462/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com