gpt4 book ai didi

javascript - 如何在 Redux 中将服务数据传递到初始状态

转载 作者:行者123 更新时间:2023-11-28 03:57:09 24 4
gpt4 key购买 nike

我有一项服务可以在购物车应用中处理我的产品数据。我想要的是将 getProducts() 方法生成的一些数据传递到应用程序 Redux 部分的初始状态

我的服务:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Http, HttpModule, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';

import 'rxjs/add/operator/map';


@Injectable()
export class ProductsService {

private products = new BehaviorSubject<any>([]);

product = this.products.asObservable();
dataUrl = "./assets/products.json";

constructor( private _http: Http ) { }

getProducts(): Observable<any>{
return this._http.get(this.dataUrl)
.map((res: Response) => res.json());
}

updateProducts(product){
this.products.next(product);
}

}

我的商店:

import { IProduct } from './product';
import { ADD_PRODUCT, REMOVE_PRODUCT, REMOVE_ALL_PRODUCTS } from './actions';
import { ProductsService } from './service/products.service';

export class IAppState {
products: IProduct[];
}

export const INITIAL_STATE: IAppState = {
constructror(private _prods: ProductsService){ }
products = this._prods.getProducts()
}


export function rootReducer(state, action){
switch(action.type){
case ADD_PRODUCT:
action.product.id = state.products.length + 1;
action.product.isAdded = true;
console.log(state.products)
return Object.assign({}, state, {
products: state.products.concat(Object.assign({}, action.product))
})

case REMOVE_PRODUCT:
action.product.isAdded = false;
return Object.assign({}, state, {
products: state.products.filter(p => p.id !== action.id)
})

case REMOVE_ALL_PRODUCTS:
return Object.assign({}, state, {
products:[]
})
}
return state;
}

但是编译器告诉

中有一个错误(意外的标记)
constructror(private _prods: ProductsService){ }

那么如何正确地将数据从我的服务传递到初始状态

最佳答案

试试这个:

import {provideStore, INITIAL_STATE} from "@ngrx/store";

bootstrap(App, [
provideStore({counter}),
provide(INITIAL_STATE, {
deps: [MyCounterService],
useFactory(counterService){
return {counter: service.getCounterValue()};
}])
});

关于javascript - 如何在 Redux 中将服务数据传递到初始状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47478715/

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