我有这个Angular 2应用程序可以工作。我正在尝试将@ ngrx/store添加到应用程序,但看起来我无法使其工作。 这是我不得不远:无法使@ 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;
}
}
亲duct.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>
我觉得我几乎没有,因为{{产品| async}}显示结果。我只是没有看到* ngFor的错误:
ORIGINAL EXCEPTION:无法找到类型为'object'的不同支持对象'[object Object]'。 NgFor仅支持与阵列等Iterables绑定。
我的意思是我理解它的意思,但我不知道为什么我得到这个。我觉得我有什么的TUTOS显示...
链接我用:
- http://onehungrymind.com/build-better-angular-2-application-redux-ngrx/
- Angular2 + ngrx/store for handling failure HTTP requests
- https://egghead.io/courses/building-a-time-machine-with-angular-2-and-rxjs
不幸的是,几乎所有的东西已经过时(不是RC5)。
更新:我理解,如果我做{{产品|异步| json}}在我的html文件中,我得到所有数据。所以它的工作,我没有得到为什么我得到这个错误* ngFor。
这似乎缺少一个空格:'让productof products' – cartant
你是对的感谢。在提出问题时这是一个错误。 – Tom
如果使用更简单的方法测试它会发生什么情况,如下所示:'
- {{product | json}}
'? – cartant