带有Angular 2的@ngrx / store:无法读取undefined的属性

时间:2016-08-18 16:32:04

标签: javascript angularjs angular ngrx

我正在尝试使用Angular 2 - RC4学习@ ngrx / store。我有一个我正在从我的组件调用的服务,而我只是试图在每次更改时控制记录列表。

车辆

export interface Vehicle {
  ...stuff...
}

车辆减速机

import { Vehicle } from '../models';

export interface VehiclesState {
  vins: string[];
  vehicles: { [vin: string]: Vehicle };
}

const initialState: VehiclesState = {
  vins: [],
  vehicles: {}
}

export const vehicles = (state: any = initialState, {type, payload}) => {
  switch (type) {
    case 'LOAD_VEHICLES':
      const vehicles: Vehicle[] = payload;
      const newVehicles = vehicles.filter(vehicle => !state.vehicles[vehicle.vin]);

      const newVehicleVins = newVehicles.map(vehicle => vehicle.vin);
      const newVehiclesList = newVehicles.reduce((vehicles: { [vin: string]: Vehicle }, vehicle: Vehicle) => {
        return mergeObjects(vehicles, {
          [vehicle.vin]: vehicle
        });
      }, {});

      return {
        vins: [...state.vins, ...newVehicleVins],
        vehicles: mergeObjects({}, state.vehicles, newVehiclesList)
      }
  }
}

main.ts

import { bootstrap } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { HTTP_PROVIDERS } from '@angular/http';
import { provideStore } from '@ngrx/store'

import { AppComponent, environment } from './app/';
import { vehicles } from './app/shared/reducers/vehicles'

if (environment.production) {
  enableProdMode();
}

bootstrap(AppComponent,
  [
    HTTP_PROVIDERS,
    provideStore(vehicles, {
      vins: [],
      vehicles: {}
    })
  ]
);

VehiclesService

import {Http, Headers} from '@angular/http';
import {Injectable} from '@angular/core';
import {Store} from '@ngrx/store';
import {Observable} from "rxjs/Observable";
import 'rxjs/add/operator/map';

import {Vehicle} from '../models/vehicle.model';

const BASE_URL = 'http://localhost:3000/vehicles/';
const HEADER = { headers: new Headers({ 'Content-Type': 'application/json' }) };

@Injectable()
export class VehiclesService {
  vehicles: Observable<Array<Vehicle>>;

  constructor(private http: Http, private store: Store<Vehicle[]>) {
    this.vehicles = this.store.select('vehicles');
  }

  loadVehicles() {
    this.http.get(BASE_URL)
      .map(res => res.json())
      .map(payload => ({ type: 'LOAD_VEHICLES', payload: payload }))
      .subscribe(action => this.store.dispatch(action));
  }
}

AppComponent

import { Component, OnInit, Input } from '@angular/core';
import { Observable } from "rxjs/Observable";
import { Store } from '@ngrx/store';

import { Vehicle, VehiclesService } from './shared';

@Component({
  moduleId: module.id,
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css'],
  providers: [VehiclesService]
})
export class AppComponent implements OnInit{
  title = 'app works!';

  vehicles: Observable<Vehicle[]>;

  constructor(private vehiclesService: VehiclesService) {
    this.vehicles = vehiclesService.vehicles;

    vehiclesService.loadVehicles();
  }

  ngOnInit() {
    console.log(this.vehicles)
    this.vehicles.subscribe(vehicles => console.log(vehicles));
  }
}

但是当它运行时,我得到一个TypeError TypeError: Cannot read property 'vehicles' of undefined

第一个console.log返回一个Store对象,但订阅似乎失败了。

知道我做错了吗?

4 个答案:

答案 0 :(得分:2)

您需要将provideStore更改为provideStore({vehicles: vehicles})

答案 1 :(得分:1)

在我的例子中,错误是在reducer对象和接口中使用了不同的名称:

import { LeaderboardParticipant } from './...';
import * as fromLeaderboard from './...';

export interface IState {
    leaderboard: fromLeaderboard.IState;
}

export const reducers = {
    leaderboard: fromLeaderboard.reducer // I used to have 'search' instead of 'leaderboard'
};

export function selectChallengeId(state: IState): string {
    return state.leaderboard.challengeId;
}

export function selectFilterTerms(state: IState): string {
    return state.leaderboard.filterTerms;
}

答案 2 :(得分:0)

信息不足:问题中缺少模板app.component.ts

但是,请检查您如何访问模板中的成员vehicles。尝试操作符?.而不是.。类似的东西:

{{ yourObject?.vehicles }}

答案 3 :(得分:0)

当您申报商店(商店)时,我认为正确的方法是:

constructor(private http: Http, private store: Store<VehicleState>)