Phi*_*ner 5 angular angular-router angular6 angular-resolver
我正在尝试使用解析器来根据路由包含的给定参数检索数据。
不幸的是,当我添加另一个数据流时,我的数据依赖于解析器从未真正解析过。
如果我直接返回一个立即解决的值,一切正常。我调试了这种情况,看到我收到了所有部分信息,但最终未能真正解决。
这是一个快速示例。如果需要更多代码来理解问题,请联系我。
我的服务:
export class MyService {
get(bar) {
return of(new Foo(bar));
}
}
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
解析器:
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'));
}
}
Run Code Online (Sandbox Code Playgroud)
路由器:
const routes: Routes = [
{
path: 'someroute',
component: SomeComponent,
canActivate: [SomeGuard],
resolve: {
myData: MyResolver,
},
},
];
Run Code Online (Sandbox Code Playgroud)
成分:
export class SomeComponent implements OnInit {
constructor(private readonly _route: ActivatedRoute) {}
ngOnInit() {
this._route.data
.subscribe((data) => {
console.log('received:', data);
this.myData = data;
});
}
}
Run Code Online (Sandbox Code Playgroud)
一些组件.html
<pre *ngIf="myData">
Received: {{ myData | json }}
</pre>
Run Code Online (Sandbox Code Playgroud)
Phi*_*ner 10
我的问题的答案相当简单,与订阅已解决的 observable 无关,因为框架已经自动做到了这一点。
为了让解析器完成,它所依赖的所有流都需要complete. 如果您碰巧使用了热可观察对象,则需要使用另一个运算符,例如,take以便流在该位置完成。
因此,所有代码都保持不变,只是我将解析器更改为:
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Foo> {
return this._secondService
.observable()
.pipe(
take(1),
switchMap((bar) => this._myService.get(bar)),
);
}
Run Code Online (Sandbox Code Playgroud)
@eduPeeth:感谢您的回答/建议,不幸的是,这是一个小得多的问题。
| 归档时间: |
|
| 查看次数: |
1715 次 |
| 最近记录: |