I have a very simple http service:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from '../../environments/environment';
import { JsOrder } from '../stores/models/order';
@Injectable({
providedIn: 'root'
})
export class OrderService {
private ordersUrl = `${environment.httpApiUrl}/orders`;
constructor(private http: HttpClient) {}
fetchOrders(): Observable<JsOrder[]> {
return this.http.get<JsOrder[]>(this.ordersUrl);
}
}
I am trying to call it from @ngrx/effects (based on several examples on the web):
import { Injectable } from '@angular/core';
import { Actions, Effect, ofType } from '@ngrx/effects';
import { Action } from '@ngrx/store';
import { Observable } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { FETCH_ORDERS, LoadOrders } from '../actions';
import { JsOrder, Order } from '../models/order';
import { OrderService } from '../../services/order.service';
@Injectable()
export class OrderEffects {
constructor(
private actions$: Actions,
private orderService: OrderService
) {}
@Effect()
fetchOrders$: Observable<Action> = this.actions$.pipe(
ofType(FETCH_ORDERS),
switchMap(() => {
return this.orderService
.fetchOrders()
.map((jsOrders: JsOrder[]) => { <---- compilation error here
const orders = jsOrders.map(jsOrder =>
Order.create(jsOrder)
);
return new LoadOrders(orders);
});
})
);
}
However I am getting a compilation error on the .map()
call above:
error TS2339: Property 'map' does not exist on type 'Observable'
What's the correct way to do this?
P.S. I also tried to subscribe()
to the Observable returned by the http service (see below), but that too gives a compile error (property 'map' does not exist on type 'Subscription'):
@Effect()
fetchOrders$: Observable<Action> = this.actions$.pipe(
ofType(FETCH_ORDERS),
switchMap(() => {
return this.orderService
.fetchOrders()
.subscribe((jsOrders: JsOrder[]) => {
return jsOrders.map(jsOrder => Order.create(jsOrder));
})
.map((orders: Order[]) => new LoadOrders(orders));
})
);
You have to use pipe
and the pipeable operators:
@Effect()
fetchOrders$: Observable<Action> = this.actions$.pipe(
ofType(FETCH_ORDERS),
switchMap(() => {
return this.orderService
.fetchOrders()
.pipe(
map((jsOrders: JsOrder[]) => {
const orders = jsOrders.map(jsOrder =>
Order.create(jsOrder)
);
return new LoadOrders(orders);
}),
catchError(err => of(new LoadOrdersFailure(err)))
)
})
);
Also don't forget to catch the errors.