我正在阅读并尝试NGXS的文档:https://www.ngxs.io/concepts/select
除了我这样做是为了我的AuthState。
我已经实现了AuthStateModel和AuthState:
import { AngularFireAuth } from '@angular/fire/auth';
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';
import { Action, NgxsOnInit, Selector, State, StateContext } from '@ngxs/store';
import { profile } from 'console';
import { User } from 'firebase';
import { LoginWithPasswordAction, RegisterAction, SendLostPasswordAction, SignoutAction } from './auth.actions';
import { Profile } from './auth.model';
import { emailToGravatarUrl } from 'email-gravatar';
import { switchMap } from 'rxjs/operators';
import { Observable, of, Subscription } from 'rxjs';
import { Injectable, OnDestroy } from '@angular/core';
export interface AuthStateModel {
profile: Profile | null;
loaded: boolean;
}
@State<AuthStateModel>({
name: 'auth',
defaults: {
profile: null,
loaded: false,
},
})
@Injectable()
export class AuthState implements NgxsOnInit, OnDestroy {
private profileSubscription: Subscription;
constructor(private angularFireAuth: AngularFireAuth, private angularFireStore: AngularFirestore) {}
ngOnDestroy(): void {
//some cleaning
}
ngxsOnInit(ctx?: StateContext<any>) {
//Some init
}
/// Some actions...
}
但现在在我的app.component.ts中,我很难选择。
根据他们的说法,我应该能够做一些类似的事情:
@Select(AuthState.profile.displayName) name$: Observable<string>;
但VS Code说(就我所见,我同意(;配置文件";在AuthState上,这是正确的,因为AuthModel上存在此属性。
我看过之后的记忆化选择器,但这并不是真正的重点。我还试着制作一个返回Profile的程序,然后只使用AuthState.Profile.displayName,但在displayName上的结果相同。
我错过了什么?
要只选择状态的profile
部分,最简单/最简单的方法是定义一个选择器
@Selector()
static profile(state: AuthStateModel): Profile {
return state.profile;
}
然后,您可以通过示例@Select(AuthState.profile)
中的静态引用在组件中使用它
或者,您可以直接@Select(state => state.profile.displayName)
,或者创建一个可观察的项目来投影您需要的东西:
@Select(AuthState) authState$: Observable<AuthStateModel>;
displayName$: Observable<string>;
ngOnInit(): void {
this.displayName$ = this.authState$.pipe(
filter(state => !!state.profile),
map(state => state.profile.displayName),
);
}