我在购物车应用中获得了与产品数据配合使用的服务。
我想要的是将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){ }
那么如何正确地将数据从我的服务传递到初始状态?
答案 0 :(得分:0)
试试这个:
import {provideStore, INITIAL_STATE} from "@ngrx/store";
bootstrap(App, [
provideStore({counter}),
provide(INITIAL_STATE, {
deps: [MyCounterService],
useFactory(counterService){
return {counter: service.getCounterValue()};
}])
});