如何使用简单的http调用@ ngrx / effects?

问题描述 投票:0回答:1

我有一个非常简单的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:类型'Observable'上不存在属性'map'

这样做的正确方法是什么?

附:我也尝试将subscribe()发送到http服务返回的Observable(见下文),但这也给出了编译错误(属性'map'在'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));
    })
);
angular6 ngrx ngrx-effects
1个回答
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)))
            )
    })
);

另外别忘了抓错误。

© www.soinside.com 2019 - 2024. All rights reserved.