7.4 RXJS : Hay dùng Gọi request - quan1997ap/angular-app-note GitHub Wiki

1. Gọi request lồng nhau - tuần tự

    this.searchField1 = new FormControl();
    this.searchField2 = new FormControl();

    this.combinedValue = this.searchField1.valueChanges.pipe(
      mergeMap(s1 => this.searchField2.valueChanges.pipe(
            map(s2 => s1 + '' + s2))  
     )
    )

2. Gọi request đồng thời trả về mảng kết quả của request

    const character = this.http.get('https://swapi.co/api/people/1');
    const characterHomeworld = this.http.get('http://swapi.co/api/planets/1');

    forkJoin([character, characterHomeworld]).subscribe(results => {
      console.log('character', results[0]);
      console.log('characterHomeworld', results[1]);
    });

3. CombineLated luôn trả về data ( custom data)

image

#4. No catch error

import { EMPTY } from 'rxjs';

function getUser(){
  return this.http.get( url ).pipe(
    map( ... ),
    catchError( () => EMPTY )
  )
}

getUser().subscrible(
  res => {}
  error => { // Error will not working }
)

5. Subscribe form change and call API

https://stackblitz.com/edit/angular-debounce-switchmap-search?file=src%2Fapp%2Fapp.component.html

  1. html
<form>
	<mat-form-field>
		<input type="text" placeholder="Country" matInput [formControl]="countryControl" [matAutocomplete]="auto">
		<mat-autocomplete #auto="matAutocomplete">
			<mat-option *ngFor="let option of filteredVaules | async" [value]="option">
				{{option}}
			</mat-option>
		</mat-autocomplete>
	</mat-form-field>
</form>
  1. ts
export class AppComponent {
  filteredVaules: Observable<string[]>;
  countryControl: FormControl = new FormControl();

  constructor(private _dataService: DataService) {}

  ngOnInit() {
    // Cách 1: 
    /*
     this.filteredVaules = this.countryControl.valueChanges.pipe(
      debounceTime(300),
      switchMap(val => this._dataService.GetFilteredCountries(val))
    );*/


    // Cách 2: 
    this.countryControl.valueChanges.pipe(debounceTime(500)).subscribe(val => {
      console.log(val);
      this.filteredVaules = this._dataService.GetFilteredCountries(val);
    });
  }
}



⚠️ **GitHub.com Fallback** ⚠️