我正在尝试使用解析器来根据路由保存的给定参数检索数据。
不幸的是,当我添加另一个数据流时,我的数据依赖于解析器,但实际上从未解析。
如果我直接返回一个立即解析值,一切都会正常。
我调试了这种情况,发现我收到了所有部分信息,但最终未能真正解决。
这是一个快速示例。如果需要更多代码来理解问题,请联系我。
我的服务:
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'));
}
}
Router:
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;
});
}
}
一些组件.html
<pre *ngIf="myData">
Received: {{ myData | json }}
</pre>