gpt4 book ai didi

angular6 - 如何通过简单的 http 调用使用 @ngrx/effects?

转载 作者:行者123 更新时间:2023-12-04 02:57:35 27 4
gpt4 key购买 nike

我有一个非常简单的 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() 上遇到编译错误上面调用:

error TS2339: Property 'map' does not exist on type 'Observable'



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

附注我也试过 subscribe()到 http 服务返回的 Observable(见下文),但这也会产生编译错误(“订阅”类型上不存在属性“ 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)))
)
})
);

也不要忘记捕捉错误。

关于angular6 - 如何通过简单的 http 调用使用 @ngrx/effects?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52212159/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com