在Angular中使用ngrx进行嵌套的HTTP调用,您可以按照以下步骤进行解决:
npm install @ngrx/store @ngrx/effects
user.actions.ts
的文件,用于定义用户相关的动作。在该文件中,定义一个名为LoadUser
的动作,用于加载用户数据。import { Action } from '@ngrx/store';
export enum UserActionTypes {
LoadUser = '[User] Load User',
UserLoaded = '[User] User Loaded',
UserLoadFailed = '[User] User Load Failed'
}
export class LoadUser implements Action {
readonly type = UserActionTypes.LoadUser;
constructor(public payload: { userId: number }) {}
}
export class UserLoaded implements Action {
readonly type = UserActionTypes.UserLoaded;
constructor(public payload: { user: any }) {}
}
export class UserLoadFailed implements Action {
readonly type = UserActionTypes.UserLoadFailed;
constructor(public payload: { error: any }) {}
}
export type UserActions = LoadUser | UserLoaded | UserLoadFailed;
user.effects.ts
的文件,用于处理用户相关的副作用。在该文件中,定义一个名为loadUser$
的效果,用于处理LoadUser
动作,并发出UserLoaded
或UserLoadFailed
动作。import { Injectable } from '@angular/core';
import { Actions, Effect, ofType } from '@ngrx/effects';
import { of } from 'rxjs';
import { switchMap, map, catchError } from 'rxjs/operators';
import { UserService } from './user.service';
import { LoadUser, UserLoaded, UserLoadFailed, UserActionTypes } from './user.actions';
@Injectable()
export class UserEffects {
constructor(private actions$: Actions, private userService: UserService) {}
@Effect()
loadUser$ = this.actions$.pipe(
ofType(UserActionTypes.LoadUser),
switchMap(action =>
this.userService.getUser(action.payload.userId).pipe(
map(user => new UserLoaded({ user })),
catchError(error => of(new UserLoadFailed({ error })))
)
)
);
}
user.service.ts
的文件,用于处理用户相关的HTTP请求。在该文件中,定义一个名为getUser
的方法,用于获取用户数据。import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class UserService {
constructor(private http: HttpClient) {}
getUser(userId: number): Observable {
return this.http.get(`/api/users/${userId}`);
}
}
import { NgModule } from '@angular/core';
import { StoreModule } from '@ngrx/store';
import { EffectsModule } from '@ngrx/effects';
import { userReducer } from './user.reducer';
import { UserEffects } from './user.effects';
@NgModule({
imports: [
StoreModule.forFeature('user', userReducer),
EffectsModule.forFeature([UserEffects])
]
})
export class UserModule {}
LoadUser
动作,并通过ngrx/effects来处理加载用户的副作用。import { Component } from '@angular/core';
import { Store } from '@ngrx/store';
import { LoadUser } from './user.actions';
@Component({
selector: 'app-user',
template: `
`
})
export class UserComponent {
constructor(private store: Store) {}
loadUser() {
this.store.dispatch(new LoadUser({ userId: 1 }));
}
}
通过上述步骤,您可以在Angular中使用ngrx进行嵌套的HTTP调用。当您点击"Load User"按钮时,将触发LoadUser
动作,并通过ngrx/effects处理副作用,从而加载用户数据。