有关某些Rxjs角度代码的语法的问题

时间:2019-08-26 10:55:07

标签: angular rxjs

我正在研究Reactive编程,发现了这段代码,谁能解释这行代码中的内容,语法的含义

const getCars = query => of(cars.filter(car => isCarMatching(car, query))).pipe(delay(3000));

是从这里来的 https://blog.angularindepth.com/rxjs-live-search-the-devil-is-in-the-detail-119637186427

完整代码

const { fromEvent, of } = rxjs;
const {
  delay,
  tap,
  map,
  filter,
  debounceTime,
  distinctUntilChanged,
  switchMap
} = rxjs.operators;

const cars = [
  {
    id: 1,
    brand: 'Ferrari',
    model: 'F40'
  },
  {
    id: 2,
    brand: 'Ferrari',
    model: 'F50'
  },
  {
    id: 3,
    brand: 'Ferrari',
    model: 'California'
  },
  {
    id: 4,
    brand: 'Porsche',
    model: '911'
  },
  {
    id: 5,
    brand: 'Porsche',
    model: 'Panamera'
  }
];

const getCarFullName = ({ brand, model }) =>
  `${brand.toLowerCase()} ${model.toLowerCase()}`;

const isCarMatching = (car, query) =>
  getCarFullName(car).startsWith(query.toLowerCase());

const getCars = query =>
  of(cars.filter(car => isCarMatching(car, query))).pipe(delay(3000));

const onCarsLoadSuccess = matchingCars => console.log(matchingCars);

const carSearch$ = fromEvent(carSearch, 'input').pipe(
  map(event => event.target.value),
  filter(query => query),
  debounceTime(1000),
  distinctUntilChanged(),
  tap(query => console.log(`About to make an API call with query: ${query}`)),
  switchMap(getCars)
);

carSearch$.subscribe(onCarsLoadSuccess);

1 个答案:

答案 0 :(得分:1)

const getCars = query =>...
//it's
getCars(query)
{
  return ...
}

of(...)
is an observable of the inside parenthesis, e.g.
of({name:"name",surname:"surname"}), return an observable you can subscribe
of({name:"name",surname:"surname"}).susbcribe(res=>{
    console.log(res) //return {name:"name",surname:"surname"}
})

cars.filter(car => isCarMatching(car, query))
return the objects in array cars that calling the function "isCarMatthing" return true
NOTE: Not use this.isCarMatching because we are not in a component is a constant

pipe(delay(3000)) is an rxjs operators that delay the response 3000 miliseconds