You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
demo1.tsimportSimpleObservablefrom'./SimpleObservable';letsubscriptions=[];letheaderTitleObservable=newSimpleObservable();letheaderTitle_subscriptsion=headerTitleObservable.subscribe(_title=>{console.log(`the header title is change to${_title}`);});subscriptions.push(headerTitle_subscriptsion);// 触发this.headerTitleObservable.next('page1');// 在组件生命周期结束时,清除所有observerssubscriptions.forEach(subscription=>{subscription.unsubscribe();});
目前对观察订阅者模式的一些体会和应用场景
1、监听
以前在用vue重构我的项目时,自己写一个类似rxjs的简单版SimpleObservable,用于实现header title等的监听,因为在我的项目中,不同页面的header只有title文字不一样,比如page1显示的titile是'page1',于是我把header做成了一个组件,而每个页面也是一个组件,因此通过SimpleObservable就可以实现组件与组件间的间接单向通信,即观察者(observer)监听被观察者(observable),被观察者触发观察者。
(备注:以下用ts语法,可以通过tsc编译生成对应js,再运行)
大致代码如下:
demo1
2、解除两个类的强耦合状态
使用观察订阅者模式,有时候能解除两个类的强耦合状态,比如,在我的项目中,我写了一个http拦截器httpInterceptor,用来过滤每一次http请求和响应,比如统一加access_token header,统一出错处理啊等等,我的httpInterceptor其中的一个功能,就是从服务器返回的响应头中检测登录状态是否已经失效或access_token是否已经过期,当检测到登录失效时,要在页面中弹出一个登录modal框(loginModalComponent),提醒用户重新登录。大致的代码如下:
(备注:以下采用ts语法,为了使理解起来更加容易,没有使用ts的依赖注入等特性)
未使用观察者模式:
demo2
以上示例代码是未使用观察者模式的情况下,需要在HttpInterceptor里new LoginModalComponent,从而导致HttpInterceptor和LoginModalComponent处于强耦合的状态,但是这样不符合HttpInterceptor拦截器的思想,因为HttpInterceptor拦截器是不应该和组件相关的东西进行耦合的,因此,采用观察者模式进行改进.
代码如下:
demo3
The text was updated successfully, but these errors were encountered: