Global data management and synchronization of updates rxjs subject Subscribe to realize Angular distribution of

Custom implementations angular state management data, please correct if wrong

First, tell us about rxjs in the subject;

Import {subject} from'rxjs' 
simulation data, subscriptions and distribution Subject, newspapers publish and subscribe binding function of the object is subject that is observeable observer objects, subject to the subscriber data is updated when there is no post-added is very friendly, because it is not with new data subscribers is not in receipt of the return value 
    const interval the $ = interval the (1000) .pipe (the Take (10)); 
    const = new new Subject Subject (); 

    const = {observerA 
      the Next: value => the console.log ( 'the Observer A GET value:' + value), 
      error: error => the console.log ( 'the Observer error A:' + error), 
      Complete: () => the console.log ( 'the Observer A Complete ! '), 
    }; 

    const = {observerB 
      Next: value => the console.log (' the Observer GET B value: '+ value), 
      error: error => the console.log (' B the Observer error: '+ error), 
      Complete : () => console.log ( 'Observer B complete!'), 
    } ; 

    Subject.subscribe (observerA); // add viewer A 
    Interval The $ .subscribe (Subject); // $ Feed interval The objects 
    the setTimeout (() => { 
      subject.subscribe (observerB); // add observer B 
    }, 1000); 

Import} {BehaviorSubject from'rxjs'; 
behaviorSubject is subject variant, the biggest difference is behaviorSubject is used to save the latest value, rather than simply sending events, the last value will be sent as the current value stored within the property. 
    const subject = new BehaviorSubject (0) ; // BehaviorSubject parentheses represents the status 0 
    const = {observerA 
      Next: value => the console.log ( 'the Observer A GET value:' + value), 
      error: error => Console. log ( 'A the Observer error:' + error), 
      Complete: ( '! Complete the Observer A') () => the console.log, 
    }; 

    const = {observerB 
      Next: value => the console.log ( 'the Observer GET value B :
      error: error => the console.log ( 'B the Observer error:' + error), 
      Complete: () => the console.log ( '! Complete the Observer B'), 
    }; 

    subject.subscribe (observerA); // add observed by A 
    // interval The $ .subscribe (subject); // $ Feed interval The objects 
    subject.next (. 1); 
    subject.next (2); 
    subject.next (. 3); 
    the setTimeout (() => { 
      subject.subscribe ( observerB); // add observer B 
    }, 1000); 

Import} {ReplaySubject from'rxjs'; 
ReplaySubject for repeatedly transmitting recent value to the subscriber 
    const subject = new ReplaySubject (2) ; // after ReplaySubject 2 is the last value transmitted twice 
    const = {observerA 
      Next: value => the console.log ( 'the Observer a GET value:' + value), 
      error: error => the console.log ( 'the Observer error A:' + error),
      Complete: () => the console.log ( 'the Observer A Complete!'), 
    }; 

    const = {observerB 
      Next: value => the console.log ( 'the Observer GET B value:' + value), 
      error: error => Console .log ( 'B the observer error:' + error), 
      Complete: () => the console.log ( '! Complete the observer B'), 
    }; 

    subject.subscribe (observerA); // add viewer A 
    // interval The $ .subscribe (subject); // $ Feed interval The objects 
    subject.next (. 1); 
    subject.next (2); 
    subject.next (. 3); 
    the setTimeout (() => { 
      subject.subscribe (observerB); // add observer B 
    }, 1000); 

Import{AsyncSubject}from’rxjs’;
AsyncSubject he returns a value after completion subject 
    const subject = new AsyncSubject ();
    const observerA = {
      next: value => console.log('Observer A get value: ' + value),
      error: error => console.log('Observer A error: ' + error),
      complete: () => console.log('Observer A complete!'),
    };

    const observerB = {
      next: value => console.log('Observer B get value: ' + value),
      error: error => console.log('Observer B error: ' + error),
      complete: () => console.log('Observer B complete!'),
    };

    subject.subscribe(observerA); // 添加观察者A
    // interval$.subscribe(subject); // 订阅interval$对象
    subject.next(1);
    subject.next(2);
    subject.next(3);
    subject.complete ();
    the setTimeout (() => { 
      subject.subscribe (observerB); // add observer B 
    }, 1000);

  We want to achieve a global data management angular need to use " BehaviorSubject "

Two, angular service files

Services in registration documents app.module.ts

import {  SomeSharedService }  from  '@shared/window-service/window.service';
providers: [
    ...
     Somekshredserviche ,
  ],

TS file: service.module.ts

import { NgModule, ModuleWithProviders } from '@angular/core';
import { SomeSharedService } from './window.service';
export { SomeSharedService };

@NgModule()
export class ServicesModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: ServicesModule,
      providers: [SomeSharedService],
    };
  }
}

TS Service File name: window.service.ts

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class SomeSharedService {
  public globalVar: BehaviorSubject<any> = new BehaviorSubject({
    dataCount1: 0,
    dataCount2: 0,
dataCount3: 0,
dataSum: 0,
}); settingKey(key, sumKey) { const globalVar = this.globalVar.getValue(); globalVar[key] -= 1; globalVar[sumKey] -= 1; this.globalVar.next(globalVar); } }

Third, global data initialization

Initialize global data in the global public assembly, specifically how to use to see how their own considerations, the data will be re-pick data to the background when the page is refreshed;

ngOnInit ():  void  {
     const  source =  timer( 030000);
     const  data =  source. pipe(
       mergeMap( val  => {
         return  this. http. get( '/admin');
      }),
       distinctUntilChanged(),
    );
     this. distinctSub =  data. subscribe( res  => {
       this. someSharedService$. globalVar. next( res. data);
    });
  }
ngOnDestroy():  void {
     this. distinctSub. unsubscribe();
  }

因为业务需要 定时向后台请求一次数据更新,所以简单写了一下 ,如果不需要就只要放一个http请求就行了;

使用  this.someSharedService$.globalVar.next(res.data); 从全局服务SomeSharedService文件中分发文件;

四、订阅服务数据

在需要的页面订阅分发内容,且会保存最后一次的数据;

import {  SomeSharedService }  from  '@shared/window-service/window.service';
constructor(
    private  someSharedService$SomeSharedService,
  ) {}
 
...
this. someSharedService. globalVar. subscribe( res  => {
       if (!( this. cdr  as  ViewRef). destroyed) {
         this. item =  res;
         this. cdr. detectChanges();
      }
    });

因为有一些数据渲染的问题 所以需要加一层判断,这就基本实现了从后台拿取数据,在多个页面进行展示;

五、实现数据修改及同步更新

import {  SomeSharedService }  from  '@shared/window-service/window.service';
constructor(
    private  someSharedService$SomeSharedService,
  ) {}
 
...
. subscribe( res  => {
         if ( res. code !==  200) {
           this. msg. error( res. message);
           return;
        }
  this. someSharedService$. settingKey( 'dataCount1''dataSum');
})
 

当完成数据请求后,调用我们内部方法,就可以在本地同步实现更新数据了;

其中原理将在后期有空时更新。

 

 

subject

Guess you like

Origin www.cnblogs.com/bomdeyada/p/11718943.html