简体   繁体   English

Angular ngrx add / del返回未定义

[英]Angular ngrx add/del returns undefined

In my app I have a list of Vehicle IDs which I get from my web api. 在我的应用程序中,我有一个从Web api获取的Vehicle ID列表。

The issue is that whenever I press my "add"-button to add an ID to my list it just adds a "undefined" to it. 问题是,每当我按下“添加”按钮将ID添加到列表中时,它只会向其中添加“未定义”。 Whenever I'm just using my plain service and subscribe to it inside my add method it works fine. 每当我只使用普通服务并在我的add方法内订阅它时,它就可以正常工作。 Same goes for my delete method. 我的删除方法也一样。

Below I present the effect and reducer from ngrx store, my service, and my add/del function. 在下面,我展示了ngrx存储,我的服务和我的add / del函数的效果和reducer。

//ngrx/store/effect
  @Injectable()
export class FavVehiclesIdEffects {
  constructor(
    private actions$: Actions,
    private vehicleService: VehicleService
  ) {}

  @Effect()
  loadFavVehiclesId$ = this.actions$
    .ofType(favVehiclesIdAction.LOAD_FAVVEHICLES_ID)
    .pipe(
      switchMap(() => {
        return this.vehicleService.getFavourite().pipe(
          map(
            favVehiclesId =>
              new favVehiclesIdAction.LoadFavVehiclesIdSuccess(favVehiclesId)
          ),
          catchError(error =>
            of(new favVehiclesIdAction.LoadFavVehiclesIdFail(error))
          )
        );
      })
    );

  @Effect()
  addFavVehiclesId$ = this.actions$
    .ofType(favVehiclesIdAction.ADD_FAVVEHICLES_ID)
    .pipe(
      map((action: favVehiclesIdAction.AddFavVehiclesId) => action.payload),
      switchMap(favvehiclesid => {
        return this.vehicleService.addVehicle(favvehiclesid).pipe(
          map(
            favvehicleid =>
              new favVehiclesIdAction.AddFavVehiclesIdSuccess(favvehicleid)
          ),
          catchError(error =>
            of(new favVehiclesIdAction.AddFavVehiclesIdFail(error))
          )
        );
      })
    );

  @Effect()
  deleteFavVehiclesId$ = this.actions$
    .ofType(favVehiclesIdAction.DELETE_FAVVEHICLES_ID)
    .pipe(
      map((action: favVehiclesIdAction.DeleteFavVehiclesId) => action.payload),
      switchMap(favvehiclesid => {
        return this.vehicleService.deleteVehicle(favvehiclesid).pipe(
          map(
            () =>
              new favVehiclesIdAction.DeleteFavVehiclesIdSuccess(favvehiclesid)
          ),
          catchError(error =>
            of(new favVehiclesIdAction.DeleteFavVehiclesIdFail(error))
          )
        );
      })
    );
}

//ngrx/store/reducer
export interface FavVehiclesIdState {
  entities: { [id: number]: Tracker };
  loaded: boolean;
  loading: boolean;
}

export const initialState: FavVehiclesIdState = {
  entities: {},
  loaded: false,
  loading: false
};

export function reducer(
  state = initialState,
  action: fromFavVehiclesId.FavVehiclesIdAction
): FavVehiclesIdState {
  switch (action.type) {
    case fromFavVehiclesId.LOAD_FAVVEHICLES_ID: {
      return {
        ...state,
        loading: true
      };
    }
    case fromFavVehiclesId.LOAD_FAVVEHICLES_ID_SUCCESS: {
      const favvehiclesid = action.payload;
      const entities = favvehiclesid.reduce(
        (entity: { [id: number]: Tracker }, favvehicleid: Tracker) => {
          return {
            ...entity,
            [favvehicleid.id]: favvehicleid
          };
        },
        {
          ...state.entities
        }
      );

      return {
        ...state,
        loaded: true,
        loading: false,
        entities
      };
    }
    case fromFavVehiclesId.LOAD_FAVVEHICLES_ID_FAIL: {
      return {
        ...state,
        loaded: false,
        loading: false
      };
    }

    case fromFavVehiclesId.ADD_FAVVEHICLES_ID_SUCCESS: {
      const favvehiclesid = action.payload;
      const entities = {
        ...state.entities,
        [favvehiclesid.id]: favvehiclesid
      };

      return {
        ...state,
        entities
      };
    }

    case fromFavVehiclesId.DELETE_FAVVEHICLES_ID_SUCCESS: {
      const favvehiclesid = action.payload;
      const { [favvehiclesid.id]: removed, ...entities } = state.entities;
      return {
        ...state,
        entities
      };
    }
  }
  return state;
}

export const getFavVehiclesIdEntities = (state: FavVehiclesIdState) =>
  state.entities;
export const getFavVehiclesIdLoaded = (state: FavVehiclesIdState) =>
  state.loaded;
export const getFavVehiclesIdLoading = (state: FavVehiclesIdState) =>
  state.loading;

//services.ts
getFavourite(): Observable<Tracker[]> {
    const url = `${this.API_URL}/favourites`;
    return this.http.get<Tracker[]>(url).pipe(
      tap(() => this.log(`fetched favVehicles id`)),
      catchError(this.handleError('getVehicles', []))
    );
  }

// Service for "add to favourite" button
  addVehicle(track: Tracker): Observable<Tracker> {
    const url = `${this.API_URL}/favourites`;
    const service = this.http.post<Tracker>(url, track, this.httpOptions).pipe(
      tap(_ => this.log(`adding vehicle id=${track.id}`)),
      catchError(this.handleError<Tracker>('addVehicle'))
    );
    console.log(service);
    return service;
  }

  // Service for "delete from favourite" button
  deleteVehicle(track: Tracker): Observable<Tracker> {
    const url = `${this.API_URL}/favourites`;
    const service = this.http.put<Tracker>(url, track, this.httpOptions).pipe(
      tap(_ => this.log(`deleted vehicle id=${track.id}`)),
      catchError(this.handleError<Tracker>('deleteVehicle'))
    );
    console.log(service);
    return service;
  }

 // component.ts
 addFav(event: VehicleDetail) {

      const temp = new Tracker();
      temp.id = event.id;

      // adding to json file
      this.store.dispatch(new fromStore.AddFavVehiclesId(temp));

      this.store.dispatch(new fromStore.LoadFavVehiclesId());

    }
  }
  // Button function which deletes the selected vehicle from your favourites
  deleteFav(event: VehicleDetail, text: string) {
      const temp = new Tracker();
      temp.id = event.id;

      // deleting from json file
      this.store.dispatch(new fromStore.DeleteFavVehiclesId(temp));

      this.store.dispatch(new fromStore.LoadFavVehiclesId());

    }
  }

My get method works fine and have never been a problem. 我的get方法工作正常,从来没有问题。 I have been wondering if my mapping I do (I take a "VehicleDetail" and remove its ID into my Tracker type, which is a object with only the property "id") causes some issues, and I have tried some variants, but overall Im quite lost since I followed along in a tutorial. 我一直在想我做的映射是否会引起问题(我采用了“ VehicleDetail”并将其ID移入我的Tracker类型,即仅具有属性“ id”的对象)会导致某些问题,并且我尝试了一些变体,但总体自从我按照教程学习以来,我很失落。 My JSON file gets updated correctly, so I believe the problem in somewhere in my ngrx store. 我的JSON文件已正确更新,因此我认为问题出在我的ngrx存储中。 What is wrong here? 怎么了 If you want me to clarify something please let me know. 如果您想让我澄清一些事情,请告诉我。

Update 更新

在此处输入图片说明

My entries are set to undefined. 我的条目设置为未定义。 Is there anyone who have noticed something wrong with my reducer file? 是否有人发现我的reducer文件有问题?

My Tracker is presented below to make everything slightly more clear: 下面显示了“我的追踪器”,以使所有内容更加清晰:

export class Tracker {
  id: number;
}

I think your logic in the reducer for adding a vehicle should look like the following: 我认为您在减速器中添加车辆的逻辑应如下所示:

case fromFavVehiclesId.ADD_FAVVEHICLES_ID_SUCCESS: {
  const favvehiclesid = action.payload;
  const entities = [...state.entities, favvehiclesid];
  return {
    ...state,
    entities
  };
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM