使用ApiService将Redux工具包方法createAsyncThunk与Angular HttpClient集成

时间:2020-07-27 12:37:07

标签: javascript angular redux redux-thunk redux-toolkit

我正在尝试在Angular应用程序中实现@reduxjs/toolkit

如何将Angular服务作为参数传递给createAsyncThunk的回调,而不是使用fetch

docs

中的示例
const fetchUserById = createAsyncThunk(
  'users/fetchById',
  async (userId: number) => {
    const response = await fetch(`https://reqres.in/api/users/${userId}`)
    // replace fetch with apiService.fetchUserById(userId)
    return (await response.json()) as MyData
  }
)

最终,我想使用HttpClientModule来获取数据。

编辑

这是我的方法,是否有更好的方法或更“角度的”方法来实现呢?

// projects.slice.ts


export const INITIAL_STATE_PROJECTS: IProjectsState = {
    projectList: [],
};

export const fetchProjects = createAsyncThunk(
    'projects/fetchProjects',
    async (projectsService: ProjectsService) => {
        const response = await projectsService.getAllProjects();
        return response;
    }
);

const projectsSlice = createSlice({
    name: 'projects',
    initialState: INITIAL_STATE_PROJECTS,
    reducers: {

    },
    extraReducers: {
        [fetchProjects.fulfilled.toString()]: (state, action) => {
            state.projectList = action.payload;
        },
    }
});

export default projectsSlice.reducer;
// projects.service.ts


@Injectable({
    providedIn: 'root'
})
export class ProjectsService {
    private serverURL = environment.api_url;
    
    constructor(private http: HttpClient) { }

    async getAllProjects(): Promise<IProject[]> {
        return new Promise((resolve, reject) => {
            const headers = new HttpHeaders();
            headers.append('Content-Type', 'application/json');
            this.http.get<IProject[]>(`${this.serverURL}/projects`, { headers, withCredentials: true })
                .subscribe(async (res) => {
                    resolve(res);
                }, (err) => {
                    reject(err);
                });
        });
    }
}

// project-list.component.ts

@Component({
    selector: 'app-project-list',
    templateUrl: './project-list.component.html',
    styleUrls: ['./project-list.component.scss']
})
export class ProjectListComponent implements OnInit {
    @select((state: IAppState) => state.projects.projectList) readonly projects$: Observable<any[]>;

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

    ngOnInit(): void {
        this.ngRedux.dispatch<any>(fetchProjects(this.projectsService));
    }
}

1 个答案:

答案 0 :(得分:0)

我希望我理解这一权利-如果不能让我知道,但是如果我知道,则可以将其包装在一个封闭的函数中:

const fetchUserById = (apiService: ApiService, userId: numer) => {
    return createAsyncThunk(
        'users/fetchById',
        async (userId: number) => {
            const response = await apiService.getUserById(userId);
            return (await response.json()) as MyData
        }
    )
}

现在您可以这样称呼它:

const user = fetchUserById(apiService, 1);