我有一个非常简单的http服务:
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);
}
}
我正试图从@ ngrx / effects调用它(基于网络上的几个示例):
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);
});
})
);
}
但是,我在上面的.map()
调用中遇到了编译错误:
错误TS2339:类型“可观察”的属性“地图”不存在
正确的方法是什么?
P.S。我还尝试subscribe()
到http服务返回的Observable(请参见下文),但这也产生了编译错误(类型“ Subscription”上不存在属性“ map”):
@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));
})
);
答案 0 :(得分:1)
您必须使用pipe
和可管道运算符:
@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)))
)
})
);
也不要忘记捕捉错误。