preface

When using frameworks like React and Vue, as projects get bigger and more complex, it’s no longer possible to express and process data through component communication, etc. You might refer to redux, Mobx, Vuex and other good open source state management libraries to manage global data state, but I also find it complicated. In Angular, however, there is a hidden mechanism for state management. Thanks to dirty checking, I later learned the great thing about Angular. I do everything for you.

Dirty inspection mechanism

I don’t really understand how it works, but it’s okay. You can think of it as using setInterval to constantly poll the state of the component to see if the property has changed. Think about it here. Because javascript variable assignments are passed by value, object references are actually pointer assignments. Suppose I refer to an external store.ts exported store in component and change the store property in Component. Will the state of other components that reference store.ts change?

test

The address of the demo

store.ts:
export let Store = {
  count:0.people:[]
}
Copy the code

All three components have the same properties and methods as component.ts

import { Component, OnInit } from '@angular/core';
import { Store } from '.. /store'
@Component({
  selector: 'app-component1'.templateUrl: './component1.component.html'.styleUrls: ['./component1.component.css']})export class Component1Component implements OnInit {
  store = Store
  constructor() { }

  ngOnInit() {
  }
  add() {
    ++this.store.count
  }
  subtract() {
    --this.store.count
  }
  
}
Copy the code

component.html

<P>Store: {{ store | json }}</P>
<button (click) ="add()">+</button>
count:{{store.count}}
<button (click) ="subtract()">-</button>
<br/>
<button (click) ="push()" >push</button>
<button (click) ="pull()" >pull</button>
Copy the code

Here’s the code I wrote. The entire app state can be saved in a single store.ts file, and comparing Redux to Mobx and the like is a hell of a lot. If used with the two-way binding [(ngModel)]=”store.count”, it’s much simpler than react and Vue code. Be careful though, for those of you who do not understand javascript value passing and reference passing, there will be some pitfalls. The store assignment in Component must be a store.ts export if you write it that way

    public store = Store.people
Copy the code

Then changing the store will not be shared with other components. For more information, see http://bosn.me/js/js-call-by-sharing.

conclusion

I really don’t understand why this is not covered on the official website, using such a cumbersome library as NGRX, and watching moOCs videos, it is not covered. Two months into Angular, I found this magic. Thankfully, I was down to a quarter of the code. By the way, I also found a magic trick using bootstrap, which will be covered in the next video. I wish you all a good year. Anyway, I’m going to see if I’ve got back from my trip.