gpt4 book ai didi

angular - BehaviorSubject 无法通过订阅接收值

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:23:08 24 4
gpt4 key购买 nike

在我的 Angular 应用程序中

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

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

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
);
});
}

routes.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 返回的数据。我需要先加载数据并显示屏幕。

最佳答案

我认为获取值的最佳方式是从 ActivatedRoute 获取它

在您的组件中,如果您注入(inject) ActivatedRoute:

constructor(ars: ActivatedRoute) {
console.log(ars.snapshot.data.data) // This will log your value here
}

这样,您就不需要 BehaviourSubject。

Here is an example on StackBlitz.

当你访问/about路由时,它会延迟2秒获取一个值来演示

关于angular - BehaviorSubject 无法通过订阅接收值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50545329/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com