angular - 如果添加了另一个数据流,解析器不会解析
问题描述
我正在尝试使用解析器来根据路由保存的给定参数检索数据。
不幸的是,当我添加另一个数据流时,我的数据依赖于解析器从未真正解析过。
如果我直接返回一个立即解析的值,一切正常。我调试了情况,看到我收到了所有的部分信息,但它最终未能真正解决。
这是一个快速示例。如果需要更多代码来理解问题,请联系我。
我的服务:
export class MyService {
get(bar) {
return of(new Foo(bar));
}
}
SecondService(这个从后端检索数据):
export class SecondService {
private readonly _observable: Observable<Bar>;
constructor() {
this._observable = merge(
// Other manipulations
).pipe(
// other manipulations
shareReplay(1)
)
}
observable(): Observable<Bar> {
return this._observable;
}
}
解析器:
export class MyResolver {
constructor(_secondService: SecondService, _myService: MyService) {}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Foo> {
// Does not work - Simply does not resolve
// return this._secondService
// .observable()
// .pipe(
// switchMap((bar) => this._myService.get(bar)),
// );
// WORKS
return of(new Foobar('sampleData'));
}
}
路由器:
const routes: Routes = [
{
path: 'someroute',
component: SomeComponent,
canActivate: [SomeGuard],
resolve: {
myData: MyResolver,
},
},
];
零件:
export class SomeComponent implements OnInit {
constructor(private readonly _route: ActivatedRoute) {}
ngOnInit() {
this._route.data
.subscribe((data) => {
console.log('received:', data);
this.myData = data;
});
}
}
SomeComponent.html
<pre *ngIf="myData">
Received: {{ myData | json }}
</pre>
解决方案
我的问题的答案相当简单,与订阅已解析的 observables 无关,因为框架已经自动完成了。
为了让解析器完成,它所依赖的所有流都需要complete
. 如果您碰巧使用热可观察对象,则需要使用另一个运算符,take
以便流在该位置完成。
因此,所有代码都保持不变,除了我将解析器更改为:
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Foo> {
return this._secondService
.observable()
.pipe(
take(1),
switchMap((bar) => this._myService.get(bar)),
);
}
@eduPeeth:感谢您的回答/建议,不幸的是,这是一个小得多的问题。
推荐阅读
- java - 如何修复“错误:二元运算符'||'的错误操作数类型 “在java中
- c++-winrt - 如何读取更新后的 C++/WinRT/XAML UWP 应用的命令行参数
- css - Semantic UI React整页网格,如何隐藏溢出的列内容?
- python - 如何在循环中增加 i 以使用 python 选择不同的列
- clion - 在 Clion 中如何导航到所有编译错误?
- javascript - 如何使用 innerHTML 更新大小为 X 的数组?
- wordpress - 建立复杂的 WooCommerce 商店的最佳方式
- javascript - 来自外部的 Reactjs Dom 操作
- java - 如何修复 @PreAuthorize 中的 SpEL 表达式?
- amazon-web-services - 我们如何在 AWS 控制台中按“最新”对 CloudWatch 流日志进行排序?