本文介绍了在BehaviorSubject中使用单个订阅变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Angular应用程序中使用BehaviorSubject,并且可以从DataService观察到Details组件,如下所示:

I use BehaviorSubject in my Angular app and I get observable to my Details component from DataService as shown below:

DataService.ts:

DataService.ts:

export class DataService {

    private messageTracker = new BehaviorSubject<any>();
    private fileTracker = new BehaviorSubject<any>();

    getMessageTracker(): Observable<any> {
        return this.messageTracker.asObservable();
    }

    getFileTracker(): Observable<any> {
        return this.fileTracker.asObservable();
    }

    //set methods omitted for brevity
}


DetailComponent:

DetailComponent :

export class DetailComponent implements OnInit {

    subscription; //??? Can I use this variable for every subscription below?

    constructor(private dataService: DataService) { }

    ngOnInit(): void {

        this.subscription = this.dataService.getMessageTracker().subscribe((param: any) => {
                //...
        });

        this.subscription = this.dataService.getFileTracker().subscribe((param: any) => {
            //...
        });
    }
}

ngOnDestroy(): void {
    this.subscription.unsubscribe();
}

我的问题是:

1)据我所知,如上所述,我应该为每个事件创建一个新的BehaviorSubject变量,例如messageCreateTracker(用于跟踪添加的新邮件),fileCreateTracker(用于跟踪添加的新文件),messageUpdateTracker(用于跟踪更新的邮件).这一切都是真的吗?

1) As far as I know, as above, I should create a new BehaviorSubject variable for each event e.g. messageCreateTracker (for tracking a new message added), fileCreateTracker (for tracking a new file added, messageUpdateTracker (for tracking a message updated). Is that all true?

2)DetailComponent中,我只为Observables的每个订阅使用了一个subscription变量.那是一个不好的方法吗?我应该为ngOnInit()中的每个订阅创建一个新的订阅变量吗?

2) Looking DetailComponent, I just used a single subscription variable for every subscriptions of Observables. Is that a bad approach? Should I create a new subscription variable for each subscriptions in ngOnInit()?

推荐答案

对查询1的回答:

取决于开发人员的编码风格,或者取决于他的想法,您还可以通过它传递事件和数据的类型,在这种情况下,您将只需要一个BehaviorSubject,例如这个:

It depends on the developer's coding style, or how he thought, you can also pass the type of event and data with that, in that case, you will need only one BehaviorSubject, like this :

this.messageTracker.next({ type : 'create' ,  data });
this.messageTracker.next({ type : 'update' ,  data });
this.messageTracker.next({ type : 'delete' ,  data });

但是如果它变大,也会产生复杂性,收益取决于项目的要求,您的方法也很好.

But this can also create a complexity if it goes large, gain depends on the requirements of the project, your way is also good.

回答查询2:

基本上,您无法处理多个订阅,因为它将覆盖前一个订阅,并且只会取消订阅最后一个订阅:

Basically, you can't handle multiple subscriptions like that it will override the previous one and it will only unsubscribe the last one :

因此,您可以为订阅的或单个数组/对象创建多个变量,然后取消所有订阅:

So you can create multiple variables for that OR single array/object of your subscription and then unsubscribe all :

使用数组:

this.subscription = [];
this.subscription.push(this.dataService.getMessageTracker().subscribe((param: any) => {}));
this.subscription.push(this.dataService.getFileTracker().subscribe((param: any) => {}));

ngOnDestroy(): void {
    this.subscription.forEach(sub => {
        sub.unsubscribe();
    })
}

使用对象:

this.subscription = {};
this.subscription['messageTracker'] = this.dataService.getMessageTracker().subscribe((param: any) => {}));
this.subscription['fileTracker'] = this.dataService.getFileTracker().subscribe((param: any) => {}));

this.subscription['fileTracker'].unsubscribe(); // <--- You can also do
delete this.subscription['fileTracker']; // <--- then dont forgot to remove, or will throw error in ngOnDestroy

ngOnDestroy(): void {
    for(key in this.subscription) {
      this.subscription[key].unsubscribe();
    }
}

这篇关于在BehaviorSubject中使用单个订阅变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 04:26