BehaviorSubject无法通过订阅接收值 [英] BehaviorSubject can not receive value with subscribe

查看:908
本文介绍了BehaviorSubject无法通过订阅接收值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我多次尝试使用BehaviorSubject获取值,以了解更改或接收值的时间。我无法在加载组件之前获取值。

I made several attempts to get the values using a BehaviorSubject to know when the value was changed or received. I can not get the values before loading the component.

通过此链接,您可以看到您要返回的内容:

Through this link you can see what you are returning:

https://dev.moip.com.br/v1。 5 / reference#listar-planos

data.service.ts:

dataOnChanged: BehaviorSubject<any> = new BehaviorSubject({});

getData() {
    return new Promise((resolve, reject) => {
        this.http.get(this.api_URL + 'plans/, this.httpOptions).subscribe((data: any) => {

            // the result is
            // data = {plans: Array(5)}

            this.dataOnChanged.next(data);
            resolve(data);
        },
            (response: any) => {
                reject(response.error);
            });
    });
}

resolve.service.ts:

constructor(
    private dataService: DataService, {
}

* Resolve
 * @param {ActivatedRouteSnapshot} route
 * @param {RouterStateSnapshot} state
 * @returns {Observable<any> | Promise<any> | any}
 */
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> | Promise<any> | any {
    return new Promise((resolve, reject) => {
        Promise.all([
            this.dataService.getData()
        ]).then(
            () => {
                resolve();
            },
            reject
        );
    });
}

路线。 module.ts:

        {
            path: 'home',
            component: HomeComponent,
            resolve: {
                data: ResolveService,
            },
        },

home。 component.ts:

constructor(
    public data: DataService,
) {

    this.dataService.dataOnChanged.subscribe((result: any) => {
        // no result
        debugger;
    });

问题是我在加载组件之前无法加载HTTP GET返回的数据。我需要先加载数据并显示屏幕。

The problem is that I can not load the data returned by HTTP GET before loading the component. I need to load the data before and show the screen.

推荐答案

BehaviorSubject 在这里是多余的,你可以使用 数据属性访问已解析的数据router / ActivatedRouteSnapshotrel =nofollow noreferrer> ActivatedRoute的快照 对象或订阅 ActivatedRoute data 保存当前路由的静态和已解析数据的属性
b $ b建议使用 Observables over promises 。通过转换为承诺,您将失去取消请求的能力以及链接RxJS运营商的能力。

Usage of BehaviorSubject is redundant over here instead you can access the resolved data using the data property of ActivatedRoute’s snapshot object or subscribe to ActivatedRoute data Property which holds the static and resolved data of the current route
it's recommended to use Observables over promises. By converting to a promise you will lose the ability to cancel a request and the ability to chain RxJS operators.

来自 文档

From Docs



  1. 依靠路由器来调用解析器。不要担心用户可以导航的所有
    方式。这是路由器的工作。
    编写此类并让路由器从那里获取它。

  1. Rely on the router to call the resolver. Don't worry about all the ways that the user could navigate away. That's the router's job. Write this class and let the router take it from there.

提供给路由器的observable必须完成。如果
observable未完成,导航将不会继续。

The observable provided to the Router must complete. If the observable does not complete, the navigation will not continue.


data.service.ts:

data.service.ts:

 getData():Observable<any> {
        return this.http.get(this.api_URL + 'plans/, this.httpOptions);
            }

resolve.service.ts:

import { Injectable } from '@angular/core';
    import { Resolve } from '@angular/router';
   import {Observable} from 'rxjs';

    @Injectable()
    export class resolver implements Resolve<Observable<any>> {
      constructor(private service:Service) {}

      resolve() {
        return this.dataService.getdata();
      }
    }

routes.module.ts:

 {
            path: 'home',
            component: HomeComponent,
            resolve: {
                data: resolver,
            },
        },

home.component.ts:,

  constructor( private route:ActivatedRoute) {
                 this.route.data.subscribe(value=>{
                       console.log(value);
                       });}

 constructor( private route:ActivatedRoute) {
                 this.item=this.route.snapshot.data;
                    console.log(this.route.snapshot.data);
                     }

STACKBLITZ DEMO

STACKBLITZ DEMO

这篇关于BehaviorSubject无法通过订阅接收值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆