我正在try 设置ngrx,而我就快完成了,我只是无法让 Select 器返回正确对象类型的可观测对象.它目前的回报率是Partial< Observable < Product > >,而不是只有Observable< Product >.

我的 Select 器代码正确吗?

模型:

export class Product {

    id: string | undefined;
    product: string | undefined;
    price: number | undefined;

    constructor(init?: Partial<any>) {

        if (init) {
            if ('id' in init) {
                this.id = init.id;
            }
            if ('product' in init) {
                this.product = init.product;
            }
            if ('price' in init) {
                this.price = init.price;
            }
        }
    }
}

我的应用程序状态:

I have several sub-states within my AppState.
I am trying to select one at a time.

export const initialState: AppState = {
    products: productsInitialState,
    customers: customersInitialState,
  }

Select 器:

export const selectProductsState = (state: AppState) => state.products;

export const selectProducts = createSelector(
  selectProductsState,
  state => new Product({id: state.id, product: state.product, price: state.price})
);

组件:

products: Product[] = [];

// I am getting an error that res is of type Partial<Observable<Product>>

this.store.select(selectProducts).subscribe((res: Product[]) => {
      this.products = blah... do manipulation of the data here...
});

推荐答案

这是一个没有使用Partial作为构造函数的例子.

最后,如您所见,我使用的是没有部分格式的订阅者.

Select 器最重要的一点是, 应该是当时给出的"国家名称" ProvideStore(...)

App.config.ts

import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';

import {
  createAction,
  createReducer,
  createSelector,
  on,
  props,
  provideStore,
} from '@ngrx/store';

import { routes } from './app.routes';

export class Product {
  id?: string;
  product?: string;
  price?: number;
  constructor(id: string, product: string, price: number) {
    this.id = id;
    this.product = product;
    this.price = price;
  }
}

export type ProductState = {
  id?: string;
  product?: string;
  price?: number;
};

export type AppState = {
  products: ProductState[];
};

export const productsInitialState = [
  {
    id: '1',
    product: 'example',
    price: 0.0,
  },
];

export const initialState: AppState = {
  products: productsInitialState,
};

export const selectProductsState = (state: AppState) => state.products;

export const selectProducts = createSelector(selectProductsState, (state) => {
  return state;
});

/**
 * Boilerplate
 */
export const action = createAction(
  '[Example consume SELECT]',
  props<Product>()
);

export const productReducer = createReducer(
  initialState,
  on(action, (state, { id, product, price }) => {
    return { ...state, products: [...state.products, { id, product, price }] };
  })
);

export const appConfig: ApplicationConfig = {
  providers: [
    provideStore({ products: productReducer }),
    provideRouter(routes),
  ],
};

App.component.ts

    import { Component } from '@angular/core';
    import { CommonModule, DecimalPipe } from '@angular/common';
    import { RouterOutlet } from '@angular/router';
    import { Store } from '@ngrx/store';
    import { AppState, Product, action, selectProducts } from './app.config';
    
    @Component({
      selector: 'app-root',
      standalone: true,
      imports: [CommonModule, DecimalPipe, RouterOutlet],
      template: `
        <h1>{{ title }}</h1>
        <ul>
          @for(product of products; track product.id) {
          <li>
            <span>
              {{ product.id }}
              {{ product.product }}
              {{ product.price | number }}
            </span>
          </li>
          } @empty { 0 products. }
        </ul>
      `,
    })
    export class AppComponent {
      title = 'ngrx-selector-returns-a-partial-object';
      products?: Product[];
      constructor(private store: Store<AppState>) {
        //Add
        this.store.dispatch(action(new Product('2', 'my new product', 0.02)));
        //Example
        this.store.select(selectProducts).subscribe({
          next: (value: any) => {
            console.dir(value);
            this.products = value.products;
          },
        });
}}

Package.json

{
  "name": "ngrx-selector-returns-a-partial-object",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^17.0.0",
    "@angular/common": "^17.0.0",
    "@angular/compiler": "^17.0.0",
    "@angular/core": "^17.0.0",
    "@angular/forms": "^17.0.0",
    "@angular/platform-browser": "^17.0.0",
    "@angular/platform-browser-dynamic": "^17.0.0",
    "@angular/router": "^17.0.0",
    "@ngrx/store": "^16.3.0",
    "@ngrx/store-devtools": "^16.3.0",
    "rxjs": "~7.8.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.14.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^17.0.1",
    "@angular/cli": "^17.0.1",
    "@angular/compiler-cli": "^17.0.0",
    "@types/jasmine": "~5.1.0",
    "jasmine-core": "~5.1.0",
    "karma": "~6.4.0",
    "karma-chrome-launcher": "~3.2.0",
    "karma-coverage": "~2.2.0",
    "karma-jasmine": "~5.1.0",
    "karma-jasmine-html-reporter": "~2.1.0",
    "typescript": "~5.2.2"
  }
}

Angular相关问答推荐

Goto锚定在嵌套容器中,具有溢出自动

有没有其他代码可以用函数的方式写成Angular ?

如何在ANGLING v17中使用鞋带样式组件?

路由在全局导航中总是给我/甚至使用相对路径

要素存储更改根存储状态

倒计时计时器,每10秒重新启动一次,共4次

在Angular 17的本地服务应用程序时禁用SSR

我需要取消订阅路由的可观察事件吗

无法创建新的 Ionic 项目

Router.navigate() 在功能拦截器内不起作用

http 调用的 RxJs 数组

将数组传递给 URLSearchParams,同时使用 http 调用获取请求

如何在 Angular Cli 中生成 .angular-cli.json 文件?

如何测试 Angular2 的 router.navigate?

请求 http.GET 时发送的 Angular2 OPTIONS 方法

实现自定义 NgbDateParserFormatter 来更改 NgbInputDatepicker 上输入值的格式是否正确?

Angular2 Base64 清理不安全的 URL 值

angular 5 material - 表单字段停留在 180px

Angular Material2 主题 - 如何设置应用程序背景?

在Angular2 Dart中设置路由和RouterLink的正确方法是什么