我的应用程序有一个NameService,用于保存名称。
App,Navbar和TheContent有两个子组件引用此服务。只要服务中的名称发生变化,我希望它在两个其他组件中更新。我怎么能这样做?
#include<iostream.h>
#include<conio.h>
void main()
{
int Track[]={10,20,30,40},*Striker;
Striker=Track;
Track[1]+=30;
cout<<"Striker >"<<*Striker<<endl;
*Striker-=10;
Striker++;
cout<<"Next @"<<*Striker<<endl;
Striker+=2;
cout<<"Last @"<<*Striker<<endl;
cout<<"Reset To"<<Track[0]<<endl;
getch();
}
答案 0 :(得分:84)
在服务中提供事件并在组件中订阅它:
@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
答案 1 :(得分:20)
由于name
中的NameService
是基本类型,因此您将在服务和组件中获得不同的实例。当您在name
中更改NameService
时,组件属性仍具有初始值,并且绑定不会按预期工作。
你应该应用angular1&#34; dot规则&#34;在这里绑定到引用类型。更改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;
}
}
答案 2 :(得分:12)
我认为Günter提供的解决方案是最好的解决方案。
那就是说,你必须意识到Angular2服务是单例,它发生在一个注入器树中。这意味着:
bootstrap
方法的第二个参数内),则实例可以由所有元素(组件和服务)共享。providers
属性中)定义服务,则该实例将特定于组件及其子组件。有关此方面的更多详细信息,您可以查看“分层依赖注入”文档:https://angular.io/docs/ts/latest/guide/hierarchical-dependency-injection.html
希望它可以帮到你, 亨利