我有这个工作的 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();
}
}
产品.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;
}
}
产品.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。
我的意思是我确实理解它的含义,但我不知道为什么会这样。我觉得我完全有 tutos 显示的内容......
我用过的链接:
- http://onehungrymind.com/build-better-angular-2-application-redux-ngrx/
- Angular2 + ngrx/store 用于处理失败的 HTTP 请求
- https://egghead.io/courses/building-a-time-machine-with-angular-2-and-rxjs
不幸的是,几乎所有东西都过时了(不是 RC5)。
更新:我只是意识到如果我这样做 {{products | 异步 | json}} 在我的 html 文件中,我得到了所有数据。所以它起作用了,我只是不明白为什么我会在 *ngFor 中出现这个错误。