[英]What is a reason to use properties of shared service in Angular as private with getters and setters?
In all the manuals shared service for passing data between the angular components should seem like below.在所有手册中,用于在角度组件之间传递数据的共享服务应如下所示。
What is a reason to use properties of shared service in Angular as private with getters and setters?将 Angular 中共享服务的属性用作 getter 和 setter 的私有属性的原因是什么?
@Injectable()
class SharedService {
private someValue$ = new BehaviorSubject<SomeType>(null);
public getSomeValue(): BehaviorSubject<SomeType> {
return this.someValue$;
}
public setSomeValue(someValue: SomeType): void {
this.someValue$.next(someValue);
}
}
The example you show is not the complete picture for a shared services pattern, although it comes close.您展示的示例并不是共享服务模式的全貌,尽管它很接近。
You normally don't pass the Subject but an Observable that comes from that Subject.您通常不会传递主题,而是传递来自该主题的 Observable。 This prevents others from directly sending info to all subscribers, but always via the Service.
这可以防止其他人直接向所有订阅者发送信息,但始终通过服务。 In that way you can filter etc what is send.
通过这种方式,您可以过滤等发送的内容。
@Injectable()
class SharedService {
private someValueSubj = new BehaviorSubject<SomeType>(null);
someValue$ = this.someValueSubj.asObservable();
public getSomeValue(): Observable<SomeType> {
return this.someValue$;
}
public setSomeValue(someValue: SomeType): void {
this.someValueSubj.next(someValue);
}
}
Furthermore this pattern is extended by having methods in the service that do something with the result being send through the Subject:此外,通过在服务中使用方法来扩展此模式,这些方法可以通过 Subject 发送结果:
@Injectable()
class SharedService {
private someValueSubj = new BehaviorSubject<SomeType>(null);
someValue$ = this.someValueSubj.asObservable();
public getSomeValue(): Observable<SomeType> {
return this.someValue$;
}
private setSomeValue(someValue: SomeType): void {
this.someValueSubj.next(someValue);
}
public doSomethingServiceLike():void{
this.setSomeValue(someType);
}
}
In this way the service can do its' "thing" and all subscribers get the result of that.通过这种方式,服务可以做它的“事情”,并且所有订阅者都会得到结果。
I hope this helps.我希望这有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.