我在Ionic-Angular应用程序中有一个组件,该组件可以在初始化时通过服务从Firestore数据库中获取项目,还可以通过服务从“用户” Firestore的集合中获取当前用户。然后,根据用户个人资料的字段,组件模板仅显示与此用户相关的项目。
一切正常,直到我注销并使用其他用户登录。似乎NgOnInit不会再次调用,因此新签名的用户有权查看以前的用户的项目。登录后,该路由将通过router.navigateByUrl(注入路由器)被路由到item组件。
我试图寻找一种强制NgOnInit的方法,并找到了一些答案,指出应在this.zone.run(()=> {}语句(已注入NgZone)内调用此页面的导航。不起作用,不会调用NgOnInit。
export class MyRequestsPage implements OnInit {
status = 'progress';
requests$: Observable<RequestData[]>;
curr_user$: Observable<Users>;
assignedRooms: string[];
isLoading: Promise<boolean>;
@ViewChild(IonSegment) segment: IonSegment;
constructor(
private requestsService: RequestsService,
private loadingCtrl: LoadingController,
public authService: AuthService,
public firestore: AngularFirestore,
private toastCtrl: ToastController
) {}
ngOnInit() {
console.log('ngoninit my-requests');
this.segment.value = 'progress';
this.requests$ = this.requestsService.getRequests();
this.curr_user$ = this.authService.getCurrUser();
this.curr_user$.subscribe(x => {
this.assignedRooms = x.rooms;
console.log('assigned rooms are: ' + this.assignedRooms);
this.isLoading = Promise.resolve(true);
console.log('is loading: ' + this.isLoading);
});
}
登录和退出功能:
login(email: string, password: string) {
return this.http
.post<AuthResponseData>(
`https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key=${
environment.firebaseAPIKey
}`,
{ email: email, password: password, returnSecureToken: true }
)
.pipe(tap(this.setUserData.bind(this)));
}
logout() {
this._user.next(null);
Plugins.Storage.remove({ key: 'authData' });
}
private setUserData(userData: AuthResponseData) {
const expirationTime = new Date(
new Date().getTime() + +userData.expiresIn * 1000
);
this._user.next(
new User(
userData.localId,
userData.email,
userData.idToken,
expirationTime
)
);
this.getUserType(userData.localId);
this.storeAuthData(
userData.localId,
userData.idToken,
expirationTime.toISOString(),
userData.email,
this.userType,
this.userName,
this.userRoom
);
}
private storeAuthData(
userId: string,
token: string,
tokenExpirationDate: string,
email: string,
userType: string,
userName: string,
userRoom: string
) {
const data = JSON.stringify({
userId: userId,
token: token,
tokenExpirationDate: tokenExpirationDate,
email: email,
userType: userType,
userName: userName,
userRoom: userRoom
});
Plugins.Storage.set({ key: 'authData', value: data });
}
实际结果:未重新创建MyRequestsPage组件-未调用NgOnInit。
预期:将基于新登录的用户调用NgOnInit并显示请求。