首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >提取订阅的值

提取订阅的值
EN

Stack Overflow用户
提问于 2019-06-04 01:41:55
回答 3查看 80关注 0票数 -2

在我的方法中我需要返回"this.profile“。但是我不能在profileObservable之外使用this.profile

代码语言:javascript
复制
  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

  }

如果你有解决方案,非常感谢

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-06-04 03:27:25

在类中创建一个方法,如下所示:

代码语言:javascript
复制
get myProfile() {
     return this.profile;
  }

您的配置文件值现在可以通过调用"myProfile()“方法来访问。

另一种选择是利用angular behaviour主题,您可以订阅该主题,以便获得最后发出的值,如:

步骤1.在你的类属性之后注册你的行为主题,如下所示:

代码语言:javascript
复制
profileSubject: BehaviorSubject<ProfileModel> = new BehaviorSubject();
profile$: Observable< ProfileModel > = this.profileSubject.asObservable();

step2。使用注册主题发出您的配置文件值:

代码语言:javascript
复制
this.profileObservable.subscribe(profile => {
   this.profileSubject.next(profile)
});

要在订阅之外访问您的配置文件值,请执行以下操作

代码语言:javascript
复制
  this.profile$.subscribe(res => {
    // the res contains your body;
   });
票数 0
EN

Stack Overflow用户

发布于 2019-06-04 02:01:08

您不能退还订阅。你的resolve返回Observable,所以你必须返回Observable值。

例如:

代码语言:javascript
复制
return this.profileObservable;
票数 0
EN

Stack Overflow用户

发布于 2019-06-04 02:56:22

你必须返回return this.profileObservable;,然后才能订阅它。另一件事是,你为什么需要这个return this.profile; //it's undefined,你可以在组件中访问任何地方的this.profile,因为它是全局变量。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56432163

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档