在我的方法中我需要返回"this.profile“。但是我不能在profileObservable之外使用this.profile
profileObservable: Observable<ProfileModel>;
profile: ProfileModel;
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<ProfileModel> {
this.store$.dispatch(new ProfileFeatureStoreActions.GetProfile());
this.profileObservable = this.store$.pipe(
select(
ProfileFeatureStoreSelectors.selectProfile
),
filter(profile => !!profile)
);
this.profileObservable.subscribe(profile => {
this.profile = profile;
console.log(this.profile) // here is defined
});
return this.profile; //it's undefined
}
如果你有解决方案,非常感谢
发布于 2019-06-04 03:27:25
在类中创建一个方法,如下所示:
get myProfile() {
return this.profile;
}
您的配置文件值现在可以通过调用"myProfile()“方法来访问。
另一种选择是利用angular behaviour主题,您可以订阅该主题,以便获得最后发出的值,如:
步骤1.在你的类属性之后注册你的行为主题,如下所示:
profileSubject: BehaviorSubject<ProfileModel> = new BehaviorSubject();
profile$: Observable< ProfileModel > = this.profileSubject.asObservable();
step2。使用注册主题发出您的配置文件值:
this.profileObservable.subscribe(profile => {
this.profileSubject.next(profile)
});
要在订阅之外访问您的配置文件值,请执行以下操作
this.profile$.subscribe(res => {
// the res contains your body;
});
发布于 2019-06-04 02:01:08
您不能退还订阅。你的resolve返回Observable,所以你必须返回Observable值。
例如:
return this.profileObservable;
发布于 2019-06-04 02:56:22
你必须返回return this.profileObservable;
,然后才能订阅它。另一件事是,你为什么需要这个return this.profile; //it's undefined
,你可以在组件中访问任何地方的this.profile,因为它是全局变量。
https://stackoverflow.com/questions/56432163
复制相似问题