Skip to content

Commit 5c1f76f

Browse files
committed
m2: introduce first reducer and selector
1 parent 64fcf92 commit 5c1f76f

File tree

4 files changed

+24
-11
lines changed

4 files changed

+24
-11
lines changed

.vscode/settings.json

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"typescript.tsdk": "node_modules/typescript/lib"
3+
}

src/app/app.module.ts

+5
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@ import { CartModule } from './cart/cart.module';
88
import { MatToolbarModule, MatIconModule } from '@angular/material';
99
import { ProductDetailsModule } from './product-details/product-details.module';
1010
import { CartDetailsModule } from './cart-details/cart-details.module';
11+
import {StoreModule} from '@ngrx/store';
12+
import {StoreDevtoolsModule} from '@ngrx/store-devtools';
13+
import { reducer } from './reducer';
1114

1215
@NgModule({
1316
declarations: [AppComponent],
@@ -20,6 +23,8 @@ import { CartDetailsModule } from './cart-details/cart-details.module';
2023
ProductDetailsModule,
2124
MatIconModule,
2225
MatToolbarModule,
26+
StoreModule.forRoot({products: reducer}),
27+
StoreDevtoolsModule.instrument({maxAge: 50}),
2328
],
2429
bootstrap: [AppComponent],
2530
})

src/app/home/home.component.ts

+5-11
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,15 @@
1-
import { Component, OnInit } from '@angular/core';
2-
import { Observable } from 'rxjs';
1+
import { Component } from '@angular/core';
32

43
import { Product } from '../model/product';
5-
import { data } from '../services/product-data';
6-
import { ProductService } from '../services/product.service';
4+
import { Store } from '@ngrx/store';
75

86
@Component({
97
selector: 'app-home',
108
templateUrl: './home.component.html',
119
styleUrls: ['./home.component.scss'],
1210
})
13-
export class HomeComponent implements OnInit {
14-
products$: Observable<Product[]>;
11+
export class HomeComponent {
12+
products$ = this.store.select(state => state.products);
1513

16-
constructor(private readonly productService: ProductService) {}
17-
18-
ngOnInit() {
19-
this.products$ = this.productService.getProducts();
20-
}
14+
constructor(private readonly store: Store<{ products: Product[] }>) {}
2115
}

src/app/reducer.ts

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import {Action} from '@ngrx/store';
2+
import {Product} from './model/product';
3+
import {data} from './services/product-data';
4+
5+
type ProductState = Product[];
6+
const initState: ProductState = data;
7+
8+
export function reducer(
9+
state: ProductState = initState, action: Action): ProductState {
10+
return state;
11+
}

0 commit comments

Comments
 (0)