2

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: {}
    })
  ]
);

車両サービス

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

4 に答える 4

2

に変更する必要がありprovideStoreますprovideStore({vehicles: vehicles})

于 2016-08-18T20:01:53.320 に答える
1

私の場合、エラーはレデューサー オブジェクトとインターフェイスで異なる名前を使用したことでした。

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;
}
于 2017-06-28T23:26:35.817 に答える
0

Store (Store) を宣言するとき、正しい方法は次のとおりだと思います。

constructor(private http: Http, private store: Store<VehicleState>)
于 2017-08-26T03:35:23.313 に答える