我有一个非常简单的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/效果(基于网络上的几个例子(调用它:
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:类型"可观察"上不存在属性"映射">
正确的方法是什么?
附言我还尝试subscribe()
http 服务返回的可观察量(见下文(,但这也给出了编译错误(类型"订阅"上不存在属性"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));
})
);
您必须使用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)))
)
})
);
也不要忘记捕获错误。
我遇到了同样的问题。 同时可以告诉效果停止发送下一个动作。
只需使用调度标志:
newEffect$ = createEffect(
() => this.myAction$,
{dispatch: false}
);