简体   繁体   English

这样使用 Angular 中的 subject 有没有安全隐患?

[英]Are there any security risks using subjects in Angular this way?

Everytime I have to use a variable in different components which can be changed over time, I store that variable in a service and wrap the value in a Subject such that every component register changes when next is called.每次我必须在不同的组件中使用一个可以随时间更改的变量时,我将该变量存储在服务中并将值包装在 Subject 中,以便在调用 next 时每个组件寄存器都会更改。 But then I see tutorials where it is mentioned that one has to be careful when using subjects.但是后来我看到教程提到在使用主题时必须小心。 They do the following:他们执行以下操作:

// in some service
private subject$: Subject<any> = new Subject();
subjectAsObservable: Observable<any> = this.subject$.asObservable();

and then the observable is used in the components but then I would not be able to call next to emit new values.然后在组件中使用可观察对象,但我将无法调用next来发出新值。

Is there any risk when using subject the following way:以下方式使用主题时是否有任何风险:

// in some service
subject$: Subject<any> = new Subject();

and then subscribe to that subject in the components and if components make changes to the variable, next is called and every component that subscribes to that subject gets the new value.然后在组件中订阅该主题,如果组件对变量进行更改,则调用next并且订阅该主题的每个组件都将获得新值。

Is the following implementation different (more "secure") to the implementation above:以下实现是否与上面的实现不同(更“安全”):

private subject$: Subject<any> = new Subject();

emitNewValue(value: any): void {
    this.subject$.next(value);
}

getSubject(): Subject<any> {
    return this.subject$:
}

I do not quite get the security risks.我不太了解安全风险。 How would I deal correctly with subjects?我将如何正确处理主题?

It is about encapsulation.这是关于封装。 In larger applications, it is a good idea to have only one place that emits to the shared stream (subject), which is in the service.在较大的应用程序中,最好只有一个地方可以发送到共享的 stream(主题),它位于服务中。

Then no other component can, for example, accidentally call complete() on the subject.然后没有其他组件可以,例如,意外调用complete()主题。 In the service, just provide one method in order to emit (emitNewValue in your example).在服务中,只需提供一种方法即可发出(在您的示例中为 emitNewValue)。 A getter for the subject is not needed as exposing the subject with asObservable provides components with a read-Only copy of the subject, which they can listen/subscribe to.不需要主题的吸气剂,因为使用asObservable公开主题为组件提供了主题的只读副本,它们可以收听/订阅。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM