要在Angular 8中使用NgRx来从HTTP请求中设置状态,你可以按照以下步骤进行操作:
npm install @ngrx/store @ngrx/effects --save
user.actions.ts
的文件,并添加以下代码:import { createAction, props } from '@ngrx/store';
import { User } from './user.model';
export const getUser = createAction('[User] Get User');
export const getUserSuccess = createAction('[User] Get User Success', props<{ user: User }>());
export const getUserFailure = createAction('[User] Get User Failure', props<{ error: string }>());
@Effect()
装饰器来监听特定的action,并发送HTTP请求。例如,创建一个名为user.effects.ts
的文件,并添加以下代码:import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { of } from 'rxjs';
import { catchError, map, mergeMap } from 'rxjs/operators';
import { UserService } from './user.service';
import * as UserActions from './user.actions';
@Injectable()
export class UserEffects {
getUser$ = createEffect(() =>
this.actions$.pipe(
ofType(UserActions.getUser),
mergeMap(() =>
this.userService.getUser().pipe(
map(user => UserActions.getUserSuccess({ user })),
catchError(error => of(UserActions.getUserFailure({ error: error.message })))
)
)
)
);
constructor(
private actions$: Actions,
private userService: UserService
) {}
}
user.service.ts
的文件,并添加以下代码:import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { User } from './user.model';
@Injectable()
export class UserService {
constructor(private http: HttpClient) {}
getUser(): Observable {
return this.http.get('https://api.example.com/user');
}
}
app.module.ts
文件,并添加以下代码:import { NgModule } from '@angular/core';
import { StoreModule } from '@ngrx/store';
import { EffectsModule } from '@ngrx/effects';
import { UserEffects } from './user.effects';
import { userReducer } from './user.reducer';
@NgModule({
imports: [
StoreModule.forRoot({ user: userReducer }),
EffectsModule.forRoot([UserEffects])
]
})
export class AppModule {}
store.dispatch()
方法来分发你的action。例如,打开你的user.component.ts
文件,并添加以下代码:import { Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import { getUser } from './user.actions';
@Component({
selector: 'app-user',
template: `
`
})
export class UserComponent implements OnInit {
constructor(private store: Store) {}
ngOnInit() {
}
getUser() {
this.store.dispatch(getUser());
}
}
这样,当你点击"Get User"按钮时,NgRx将会触发getUser
action,然后effect会监听到这个action并发送HTTP请求。请求成功后,将会分发getUserSuccess
action并更新状态。如果请求失败,将会分发getUserFailure
action并设置错误信息。
请注意,上述代码仅提供了一个基本的示例,你可能需要根据你的实际需求进行适当的修改和调整。