使用redux和angular 2无法正常工作的搜索实现

时间:2018-04-16 16:44:29

标签: javascript angular redux angular5 ngrx

我正在尝试实现一个搜索,它将从存储状态中过滤值并显示在列表中,当搜索被清除时,将存储状态重置为其原始状态。

我对Redux概念比较陌生,所以我做了一个笔记应用程序,它会保存笔记,删除它们然后我去实现搜索。

  

目前没有来自后端的数据,因为这是新的POC   特征

我的store.ts如下: -



import { INote } from './note';
import { ADD_NOTE, TOGGLE_NOTE, REMOVE_NOTE, REMOVE_ALL_NOTES, SEARCH_NOTE } from './actions';

export interface IAppState {
    notes: INote[];
    lastUpdate: Date;
}

export const INITIAL_STATE: IAppState = {
   notes: [],
   lastUpdate: null
}

export function rootReducer(state, action) {
    switch(action.type) {
        case ADD_NOTE:
            action.note.id = state.notes.length + 1;
            return Object.assign({}, state, {
              notes: state.notes.concat(Object.assign({}, action.note)),
              lastUpdate: new Date()  
            });
        case TOGGLE_NOTE:
            var note = state.notes.find(t => t.id === action.id);     
            var index = state.notes.indexOf(note);
            return Object.assign({}, state, {
                notes: [
                  ...state.notes.slice(0, index),
                  Object.assign({}, note, { isCompleted: !note.isCompleted }),
                  ...state.notes.slice(index+1)
                ],
                lastUpdate: new Date()   
            });
        case REMOVE_NOTE: 
            return Object.assign({}, state, {
              notes: state.notes.filter(t => t.id !== action.id),
              lastUpdate: new Date()
            });
        case REMOVE_ALL_NOTES: 
            return Object.assign({}, state, {
              notes: [],
              lastUpdate: new Date()  
            });
        case SEARCH_NOTE:
            if(action.payload.text === "") {
                var getState = JSON.parse(localStorage.getItem("state"));
                console.log("test", getState);
                return Object.assign({}, state, getState);
            }else {
                return Object.assign({}, state, {
                    notes: state.notes.filter(t => t.description.indexOf(action.payload.text) > -1),
                    lastUpdate: new Date()
                });
            }                
    } 
    return state;
}




我的笔记列表组件如下: -



import { Component, OnInit } from '@angular/core';
import { NgRedux, select } from '@angular-redux/store';
import { IAppState } from '../store';
import { ADD_NOTE, REMOVE_NOTE, TOGGLE_NOTE } from '../actions';
import { INote } from '../note';

@Component({
  selector: 'app-note-list',
  templateUrl: './note-list.component.html',
  styleUrls: ['./note-list.component.css']
})
export class NoteListComponent implements OnInit {
  @select() notes;
  stateForLocalStorage: Array<any> = [];
  
  model: INote = {
    id: 0,
    description: "",
    responsible: "",
    priority: "low",
    isCompleted: false
  };

  constructor(private ngRedux: NgRedux<IAppState>) { }

  ngOnInit() { localStorage.clear(); }

  onSubmit() {
    let data: Object = this.ngRedux.dispatch({type: ADD_NOTE, note: this.model});
    
    let stored = JSON.parse(localStorage.getItem("store"));

    if(this.stateForLocalStorage.length == 0) {
      this.stateForLocalStorage.push(data);
      // save data to localstorage to retrieve later
      localStorage.setItem('state', JSON.stringify(this.stateForLocalStorage));
    } else if (stored !== null) {
      stored.push(data);
      // save data to localstorage to retrieve later
      localStorage.setItem('state', JSON.stringify(stored));
    }
       
  }

  toggleNote(note) {
    this.ngRedux.dispatch({type: TOGGLE_NOTE, id: note.id});
  }

  removeNote(note) {
    this.ngRedux.dispatch({type: REMOVE_NOTE, id: note.id});
  }

}
&#13;
&#13;
&#13;

note-overview组件,我在ngOnInit中调度SEARCH_NOTE操作如下: -

&#13;
&#13;
import { Component, OnInit } from '@angular/core';

// import redux, store and actions
import { NgRedux, select } from '@angular-redux/store';
import { IAppState } from '../store';
import { SEARCH_NOTE, REMOVE_ALL_NOTES } from '../actions';

// import for search from rxjs
import { Observable } from 'rxjs/Observable';
import { Subject }    from 'rxjs/Subject';
import { of }         from 'rxjs/observable/of';
import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators';

@Component({
  selector: 'app-note-overview',
  templateUrl: './note-overview.component.html',
  styleUrls: ['./note-overview.component.css']
})

export class NoteOverviewComponent implements OnInit {
  @select() notes;
  @select() lastUpdate;
  
  private searchTerms = new Subject<string>();

  constructor(private ngRedux: NgRedux<IAppState>) { }

  ngOnInit(): void {
    this.searchTerms.pipe(
      // wait 300ms after each keystroke before considering the term
      debounceTime(300),
      // ignore new term if same as previous term
      distinctUntilChanged()
    ).subscribe((text: string) => this.ngRedux.dispatch({
      type: SEARCH_NOTE,
      payload: {
          text: text
      }
    }));
    
  }

  clearNotes() {
    this.ngRedux.dispatch({ type: REMOVE_ALL_NOTES });
  }

  // Push a search term into the observable stream.
  searchNote(term: string): void { 
    this.searchTerms.next(term);
  }

}
&#13;
&#13;
&#13;

所以我尝试将每个状态数据保存到localStorage并尝试使用localStorage数据重置状态。当我搜索笔记描述时它工作正常,但当我清除搜索并尝试使用localStorage数据将状态重置为其原始状态时,我失败了。搜索也无法正常工作。

然后应该做些什么来使搜索工作。提前致谢。

我已将代码推送到我的github配置文件中,因此如果上面有任何不清楚的地方,可以访问所有代码。

https://github.com/MiHawkStackOverFlow/Angular4-Redux

0 个答案:

没有答案