Small talk:

We talked about developing Angular public components. There is one detail that I don’t know if you have noticed.

Asynchronous data transfer

Asynchronous transfers are common in Angular,

async ngOnInit():Promise<void> {
    
    do something...
    await this.another();
    //another is executed after execution
    this.then();
}

Copy the code

Let’s talk about three ways to propagate asynchronous data to components.

The first kind of

Use the * ngIf

The second,

That’s the ngOnchanges() method used above.

The third kind of

Using RxJs BehaviorSubject doesn’t know the poke of this method here. If you just new a BehaviorSubject first,

 private _data = new BehaviorSubject<any[] > ([]);Copy the code

The get() and set() methods are then used to monitor the changes.

// initialize a private variable _data, it's a BehaviorSubject
   private _data = new BehaviorSubject<Post[]>([]);

   // change data to use getter and setter
   @Input()
   set data(value) {
       // set the latest value for _data BehaviorSubject
       this._data.next(value);
   };

   get data() {
       // get the latest value from _data BehaviorSubject
       return this._data.getValue();
   }
Copy the code

And then just do it in OnInit()

  ngOnInit() {
       // now we can subscribe to it, whenever input changes, 
       this._data
           .subscribe(x= > {
           this.dataSource = x;
           });
   }

Copy the code

If you want to unsubscribe after fetching the value once, you can use the

ngOnInit() { this._data // add this line // listen to data as long as groupPosts is undefined or null // Unsubscribe once groupPosts has value .takeWle(() =>! this.dataSourceSubscription) .subscribe(x => { this.dataSourceSubscription=this.xxx(); }); }Copy the code
.takeWhile((a)= > !this.dataSourceSubscription)
Copy the code

The idea is to subscribe and unsubscribe as soon as possible. So much for that, I welcome your corrections.