类型'{{键:字符串]的参数:任意; }”不可分配给“ any []”类型的参数

时间:2019-11-23 03:29:44

标签: javascript angular typescript angular-material lodash

我正在尝试使用ngrx做一个简单的神奇宝贝应用程序。我正在使用lodash库来做一个键值数组。我几乎在填写MatTableDataSource所需的所有步骤中都取得了成功,但是我不知道如何为此输入正确的类型。因此,我需要接收我的数据并用它填充我的dataSource.data,但是我会收到此错误:“类型'{[key:string]:any;}'的参数无法分配给'any []'类型的参数。类型'{[key:string]:any;}'缺少类型'any []'中的以下属性:length,pop,push,concat和另外26个“。因此,我的表未呈现。如何为我的MatTableDataSource提供正确的类型或解决此问题?

致谢

我的Observable听到响应并将其值设置为MatTableDataSource 'pokemon.component.ts'

public readonly pokemonsSubscription = this.store.pipe(select(fromPokemons.pokemons)).subscribe(pokemons => {
    if (!pokemons || pokemons.length === 0) {
      return;
    }
    //the error is below
    this.dataSource.data = new MatTableDataSource(pokemons);

    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  });

这是我的宠物小精灵存储库'pokemon.store.ts'

export const selectPokemonsState = (appState: AppState) => appState.Pokemons;

export const pokemons = createSelector(selectPokemonsState, (pokemonsState: PokemonsState) => pokemonsState.pokemons);
export const isLoading = createSelector(selectPokemonsState, (pokemonsState: PokemonsState) => pokemonsState.isLoading);
export const initial = createSelector(selectPokemonsState, (pokemonsState: PokemonsState) => pokemonsState.initial);
export const final = createSelector(selectPokemonsState, (pokemonsState: PokemonsState) => pokemonsState.final);

这些是我的动作'pokemons.actions.ts'

export enum Action {
    PokemonsLoad = '[Pokemons] Load',
    PokemonsLoadSuccess = '[Pokemons] Load Success',
    PokemonsLoadError = '[Pokemons] Load Error',
    PokemonLoadByQuantity = '[Pokemon] Load By Quantity',
    PokemonLoadByQuantitySuccess = '[Pokemon] Load By Quantity Success',
    PokemonLoadByQuantityError = '[Pokemon] Load By Quantity Error',
}

export const PokemonsLoad = createAction(Action.PokemonsLoad);
export const PokemonsLoadSuccess = createAction(Action.PokemonsLoadSuccess, props<{ payload: Array<any> }>());
export const PokemonsLoadError = createAction(Action.PokemonsLoadError, props<{ payload: any }>());
export const PokemonLoadByQuantity = createAction(Action.PokemonLoadByQuantity, props<{ payload: { initial: number, final: number }}>());
export const PokemonLoadByQuantitySuccess = createAction(Action.PokemonLoadByQuantitySuccess, props<{ payload: Array<any> }>());
export const PokemonLoadByQuantityError = createAction(Action.PokemonsLoadError, props<{ payload: any }>());

我的减速器'pokemons.reducer.ts'

export interface PokemonsState {
    pokemons: { [key: string]: any };
    isLoading: boolean;
    initial: number;
    final: number;
    quantityOfAllPokemons: number;
}

export const pokemonsInitialState: PokemonsState = {
    pokemons: {},
    isLoading: false,
    initial: 1,
    final: 24,
    quantityOfAllPokemons: undefined,
};

const pokemonsReducer = createReducer(
    pokemonsInitialState,
    on(pokemonsActions.PokemonsLoadSuccess, (state, { payload }) => (
        {
            ...state,
            pokemons: keyBy(PokemonNumber.pokemonNumber(payload), 'id'),
            isLoading: false,
            quantityOfAllPokemons: payload.length
        }
    )
    ),
    on(pokemonsActions.PokemonLoadByQuantitySuccess, (state, { payload }) => (
        {
            ...state,
            pokemons: keyBy( Object.values(state.pokemons).concat(payload), 'id'),
            isLoading: false,
            initial: PokemonNumber.nextSearch(state.final, state.quantityOfAllPokemons, 1),
            final: PokemonNumber.nextSearch(state.final, state.quantityOfAllPokemons, 12)
        }
    )
    ),
    on(pokemonsActions.PokemonsLoad, (state) => (
        {
            ...state,
            isLoading: true
        }
    )
    ),
    on(pokemonsActions.PokemonLoadByQuantity, (state) => (
        {
            ...state,
            isLoading: true
        }
    )
    ),
);

export function reducer(pokemonState: PokemonsState | undefined, action: Action) {
    return pokemonsReducer(pokemonState, action);
}

export const pokemonsFeatureKey = 'Pokemons';

效果'pokemons.effects.ts'

@Injectable()
export class PokemonsEffects {

    loadAllPokemons$ = createEffect(() => this.actions$.pipe(
        ofType(Action.PokemonsLoad),
        switchMap((payload) => {
            return this.pokemonsService.getAllPokemons()
                .pipe(
                    map(pokemons => (PokemonsLoadSuccess({ payload: pokemons }))),
                    catchError((msg) => of(PokemonsLoadError({ payload: msg }))),
                );
        })
    )
    );

    loadPokemonByQuantity$ = createEffect(() => this.actions$.pipe(
        ofType(Action.PokemonLoadByQuantity),
        switchMap((payload) => {
            return this.pokemonsService.loadPokemonByQuantity(payload['payload']['initial'], payload['payload']['final'])
                .pipe(
                    map(pokemons => (PokemonLoadByQuantitySuccess({ payload: pokemons }))),
                    catchError((msg) => of(PokemonLoadByQuantityError({ payload: msg }))),
                );
        })
    )
    );

    success$ = createEffect(() => this.actions$.pipe(
        ofType<{ type: string, payload: any }>(
            // Action.PokemonsLoadSuccess,
            // Action.PokemonLoadByQuantitySuccess,
        ),
        tap(({ type, payload }) => { window.alert('Sucesso'); })
    ), { dispatch: false });

    error$ = createEffect(() => this.actions$.pipe(
        ofType<{ type: string, payload: string }>(
            Action.PokemonsLoadError,
            Action.PokemonLoadByQuantityError,
        ),
        tap(({ type, payload }) => { window.alert('Erro'); }),
    ), { dispatch: false });

    constructor(private actions$: Actions, private pokemonsService: PokemonsService) { }
}

关于此错误的问题我的排名是

stackblitz

2 个答案:

答案 0 :(得分:0)

该错误表明您正在尝试将一个对象分配给array类型的属性。在下面的行中:

this.dataSource.data = new MatTableDataSource(pokemons);

MatTableDataSource()需要一个数组,但似乎pockemons不是正确的对象数组。您可以通过执行console.log(Array.isArray(pockemons));来验证这一点。

一旦确认pockemons不是对象数组,就可以将该对象放入对象数组中(或发布单独的问题)。

您还应该将上面的行更改为此(删除.data):

this.dataSource = new MatTableDataSource(pokemons);

更新

在仔细检查堆栈闪电时,似乎pokemons是从商店中检索出来的,即使它是一系列对象,也不会作为对象数组出现。

答案 1 :(得分:0)

  

我正在使用lodash库来做一个键值数组

您根本不会创建数组,它实际上是对象的对象,例如:

{
    "1": {
        "name": "bulbasaur",
        "url": "https://pokeapi.co/api/v2/pokemon/1/",
        "id": 1
    },
    "2": {
        "name": "ivysaur",
        "url": "https://pokeapi.co/api/v2/pokemon/2/",
        "id": 2
    }
}

我不明白为什么您实际上需要这样做,并且根据表的设置方式,它期望像从API中获得的数组。无论如何,您都在使用pokemonNumber为您的宠物小精灵创建ID,并用来为PokemonLoadByQuantitySuccess中的每个宠物小精灵获取单独的数据。

所以我会这样做:

on(pokemonsActions.PokemonsLoadSuccess, (state, { payload }) => (
  {
    ...state,
    pokemons: PokemonNumber.pokemonNumber(payload), // <<<<<<<<<< this instead
    // pokemons: keyBy(PokemonNumber.pokemonNumber(payload), 'id'),
    isLoading: false,
    quantityOfAllPokemons: payload.length
  }
)

好的,然后在为每个宠物小精灵获取数据时,您正在使用concat,这在这里不合适,因为您只是在串联数组。您想要的是根据ID将数据附加到特定的神奇宝贝。这样做可能更清洁,但至少可以起作用:

on(pokemonsActions.PokemonLoadByQuantitySuccess, (state, { payload }) => (
  {
    ...state,
    // pokemons: keyBy( Object.values(state.pokemons).concat(payload), 'id'),
    // below instead!!
    pokemons: state.pokemons.map((p, i) => { return {... p, ...payload.find(i => i.id === p.id)}}),
    isLoading: false,
    initial: PokemonNumber.nextSearch(state.final, state.quantityOfAllPokemons, 1),
    final: PokemonNumber.nextSearch(state.final, state.quantityOfAllPokemons, 12)
  }
)

最后,就像其他答案中的data一样,来自:

this.dataSource = new MatTableDataSource(pokemons);

这似乎可行。

您分叉的STACKBLITZ

您可能需要调整商店中的loading属性,在获取所有口袋妖怪的单独数据时,当前图像会延迟显示(至少对我而言)。