puddlejumper26 / blogs

Personal Tech Blogs
4 stars 1 forks source link

Observable in Angular - When to use it #162

Open puddlejumper26 opened 3 years ago

puddlejumper26 commented 3 years ago

Angular makes use of observables as an interface to handle a variety of common asynchronous operations. For example:

<app-zippy (open)="onOpen($event)" (close)="onClose($event)"></app-zippy>
@Component({
  selector: 'app-zippy',
  template: `
    <div class="zippy">
      <div (click)="toggle()">Toggle</div>
      <div [hidden]="!visible">
        <ng-content></ng-content>
      </div>
    </div>
  `,
})
export class ZippyComponent {
  visible = true;
  @Output() open = new EventEmitter<any>();
  @Output() close = new EventEmitter<any>();

  toggle() {
    this.visible = !this.visible;
    if (this.visible) {
      this.open.emit(null);
    } else {
      this.close.emit(null);
    }
  }
}

2.0 HTTP

3.0 Async pipe

@Component({ selector: 'app-routable', templateUrl: './routable.component.html', styleUrls: ['./routable.component.css'] }) export class Routable1Component implements OnInit {

navStart: Observable;

constructor(private router: Router) { // Create a new Observable that publishes only the NavigationStart event this.navStart = router.events.pipe( filter(evt => evt instanceof NavigationStart) ) as Observable; }

ngOnInit() { this.navStart.subscribe(evt => console.log('Navigation Started!')); } }

- The `ActivatedRoute` is an injected router service that makes use of observables to get information about a route path and parameters.
```ts
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-routable',
  templateUrl: './routable.component.html',
  styleUrls: ['./routable.component.css']
})
export class Routable2Component implements OnInit {
  constructor(private activatedRoute: ActivatedRoute) {}

  ngOnInit() {
    this.activatedRoute.url
      .subscribe(url => console.log('The URL changed to: ' + url));
  }
}

5.0 Reactive forms

@Component({ selector: 'my-component', template: 'MyComponent Template' }) export class MyComponent implements OnInit { nameChangeLog: string[] = []; heroForm: FormGroup;

ngOnInit() { this.logNameChange(); } logNameChange() { const nameControl = this.heroForm.get('name'); nameControl.valueChanges.forEach( (value: string) => this.nameChangeLog.push(value) ); } }


- - - - - - - - -

# Reference
- https://angular.io/guide/observables-in-angular