我有这个Angular 2应用程序。我正在尝试将@ ngrx / store添加到应用程序中,但似乎我无法使其正常工作。 以下是我的目标:
product.component.ts
import {Component, Input, ChangeDetectionStrategy} from "@angular/core";
import {ProductService} from "../index";
declare const module;
@Component({
selector: 'products',
moduleId: module.id,
providers: [ProductService],
templateUrl: '_products.component.html',
styleUrls: ['_products.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class _ProductsComponent {
products;
constructor(private productService: ProductService) {
this.products = this.productService.products$;
this.productService.loadProducts();
}
}
product.reducer.ts
import {ActionReducer, Action} from '@ngrx/store';
import {Product} from "./index";
export const products: ActionReducer<Product> = (state: any = {}, action:Action) => {
switch (action.type) {
case 'ADD_PRODUCTS':
return action.payload;
default:
return state;
}
}
product.service.ts
import {Injectable} from "@angular/core";
import {HttpService} from "../shared/services/http.service";
import {Store} from "@ngrx/store";
import {AppStore} from "../shared/store.interface";
@Injectable()
export class ProductService {
products$;
constructor(
private store: Store<AppStore>,
private httpService: HttpService) {
this.products$ = store.select('products');
}
loadProducts() {
return this.httpService.call('get', 'home')
.map(res => res.json())
.map(payload => ({ type: 'ADD_PRODUCTS', payload }))
.subscribe(action => this.store.dispatch(action))
}
}
<div class="grid_products">
{{products | async}} // shows: [object Object],[object Object],[object Object],[object Object]....
<product*ngFor="let product of products | async" [product]="product" class="grid_product alcenter"></product> // gives me errors
</div>
我觉得我差不多因为{{products | async}}显示结果。我只是没有得到* ngFor抓住我的错误:
原始例外:无法找到'object'类型的不同支持对象'[object Object]'。 NgFor仅支持绑定到Iterables,例如Arrays。
我的意思是我明白这意味着什么,但我不知道为什么我会这样做。我觉得我完全是托特人所展示的......
我用过的链接:
不幸的是,几乎所有东西都已过时(不是RC5)。
更新:我很清楚,如果我这样做{{产品|异步| json}}在我的html文件中,我得到了所有的数据。所以它正在工作,我很难理解为什么我在* ngFor。
中得到这个错误答案 0 :(得分:0)
在reducer上,您需要将状态初始化为数组而不是对象。
现在你有
state: any = {}
成功
state: any = []
当模板最初尝试渲染html时,它试图迭代“products”的初始状态,这是一个对象而不是一个数组。
答案 1 :(得分:0)
将减速器更改为:
import {ActionReducer, Action} from '@ngrx/store';
import {Product} from "./index";
export const products: ActionReducer<Product[]> = (state: Product[] = [], action:Action) => {
switch (action.type) {
case 'ADD_PRODUCTS':
state.push(action.payload);
return state;
default:
return state;
}
}